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

前端 未结 1 1145
后悔当初
后悔当初 2021-01-14 18:20

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

相关标签:
1条回答
  • 2021-01-14 18:45

    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();
    }
    
    0 讨论(0)
提交回复
热议问题