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

Che*_*eso 3 .net richtextbox winforms

我想滚动RichTextBox,以使插入符号大约位于RichTextBox的中间.

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

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

Che*_*eso 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,如果要将插入符号滚动到富文本框顶部的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();
}
Run Code Online (Sandbox Code Playgroud)