R – Winforms RichTextBox: How to scroll the caret to the middle of the RichTextBox

netrichtextboxwinforms

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.

Best Answer

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