Winforms RichTextBox: How can I scroll the caret to the middle of the RichTextBox?

偶尔善良 提交于 2019-12-04 01:42:56

问题


I want to scroll a RichTextBox so that the caret is approximately in the middle of the RichTextBox.

Something like RichTextBox.ScrollToCaret(), except I don't want to put the caret at the very top.

I saw Winforms: Screen Location of Caret Position, and of course also saw the Win32 function SetCaretPos(). But I'm not sure how to translate the x,y required by SetCaretPos into lines in the richtextbox.


回答1:


If the rich text box is in _rtb, then you can get the number of visible lines:

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;
    }
}

Then, if you want to scroll the caret to, say, 1/3 of the way from the top of the richtextbox, do this:

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();
}


来源:https://stackoverflow.com/questions/1773400/winforms-richtextbox-how-can-i-scroll-the-caret-to-the-middle-of-the-richtextbo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!