Winforms RichTextBox:如何将插入符号滚动到RichTextBox的中间?

时间:2009-11-20 21:38:03

标签: .net winforms richtextbox

我想滚动一个RichTextBox,以便插入符号大致位于RichTextBox的中间。

RichTextBox.ScrollToCaret()之类的东西,除了我不想把插入符号放在最顶端。

我看到Winforms: Screen Location of Caret Position,当然也看到了Win32函数SetCaretPos()。但我不确定如何将SetCaretPos所需的x,y转换为richtextbox中的行。

1 个答案:

答案 0 :(得分:6)

如果富文本框位于_rtb中,则可以获得可见行数:

public int NumberOfVisibleLines
{
    get
    {
        int topIndex = _rtb.GetCharIndexFromPosition(new System.Drawing.Point(1, 1));
        int bottomIndex = _rtb.GetCharIndexFromPosition(new System.Drawing.Point(1, _rtb.Height - 1)); 
        int topLine = _rtb.GetLineFromCharIndex(topIndex);
        int bottomLine = _rtb.GetLineFromCharIndex(bottomIndex);
        int n = bottomLine - topLine + 1;
        return n;
    }
}

然后,如果要将插入符号滚动到富文本框顶部的1/3处,请执行以下操作:

int startLine = _rtb.GetLineFromCharIndex(ix);
int numVisibleLines = NumberOfVisibleLines;

// only scroll if the line to scroll-to, is larger than the 
// the number of lines that can be displayed at once.
if (startLine > numVisibleLines)
{
    int cix = _rtb.GetFirstCharIndexFromLine(startLine - numVisibleLines/3 +1);
    _rtb.Select(cix, cix+1);
    _rtb.ScrollToCaret();
}