【问题标题】:Winforms RichTextBox: How can I scroll the caret to the middle of the RichTextBox?Winforms RichTextBox:如何将插入符号滚动到 RichTextBox 的中间?
【发布时间】:2009-11-20 21:38:02
【问题描述】:

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

类似于RichTextBox.ScrollToCaret(),但我不想将插入符号放在最顶部。

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

【问题讨论】:

    标签: .net winforms richtextbox


    【解决方案1】:

    如果富文本框在_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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      • 2010-10-28
      • 2012-09-26
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      • 2010-11-29
      相关资源
      最近更新 更多