【问题标题】:RichTextBox scroll to endRichTextBox 滚动到结尾
【发布时间】:2018-02-02 05:00:59
【问题描述】:

我有一个 RichTextBox,我想在添加新文本时自动滚动到文本末尾。

这是我的代码:

private void outputWindowTextChanged(object sender, EventArgs e) {
    rtb_outputWindow.SelectionStart = rtb_outputWindow.Text.Length;
    rtb_outputWindow.ScrollToCaret();
}

我手动将一堆文本添加到 RichTextBox,如下所示:

updateOutputWindow("Lorem ipsum dolor sit amet, ..."); //These strings are really long
updateOutputWindow("Lorem ipsum dolor sit amet, ..."); //I shortened them for this question

结果如下:

在上面的屏幕截图中,您几乎看不到边缘下方实际上还有更多文本。你也可以看看右边的滚动条,看看下面还有一点点空间。

在上面的截图中,我使用右侧的滚动条手动向下滚动到底部;显示之前隐藏的文字。

有没有办法确保 RichTextBox 每次都自动滚动到最后?

【问题讨论】:

  • 不确定这是否有效,但尝试将插入符号位置设置到文本框的末尾:rtb_outputWindow.CaretPosition = rtb_outputWindow.CaretPosition.DocumentEnd;
  • @TimothyGroote RichTextBox 不包含“CaretPosition”的定义。
  • @imsome1 如果您指的是该线程的已接受答案,那么这正是我目前正在做的事情。
  • 尝试在您最后一次调用updateOutputWindow之后直接放置您的“设置插入符号并滚动到它”代码

标签: c# scroll richtextbox


【解决方案1】:

改编自this answer,解决了最后一行有时被截断的问题。

我将答案扩展为TextBoxBase 上的扩展方法,以便它可以同时用于TextBoxRichTextBox

用法:

rtb_outputWindow.ScrollToBottom();

实施:

public static class RichTextBoxUtils
{
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    private static extern int SendMessage(System.IntPtr hWnd, int wMsg, System.IntPtr wParam, System.IntPtr lParam);

    private const int WM_VSCROLL = 0x115;
    private const int SB_BOTTOM = 7;

    /// <summary>
    /// Scrolls the vertical scroll bar of a text box to the bottom.
    /// </summary>
    /// <param name="tb">The text box base to scroll</param>
    public static void ScrollToBottom(this System.Windows.Forms.TextBoxBase tb)
    {
        if (System.Environment.OSVersion.Platform != System.PlatformID.Unix)
            SendMessage(tb.Handle, WM_VSCROLL, new System.IntPtr(SB_BOTTOM), System.IntPtr.Zero);
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 2011-10-18
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多