简体   繁体   English

RichTextBox滚动到结束

[英]RichTextBox scroll to end

I have a RichTextBox which I want to automatically scroll to the end of the text, when new text gets added. 我有一个RichTextBox,当添加新文本时,我想自动滚动到文本的末尾。

Here is my code: 这是我的代码:

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

I manually add a bunch of text to the RichTextBox, like so: 我手动将一堆文本添加到RichTextBox中,如下所示:

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

Here is the result: 结果如下:

screenshot1

In the above screenshot you can just barely make out that there is actually more text underneath the edge. 在上面的屏幕截图中,您几乎无法确定边缘下方实际上有更多文本。 You can also look at the scroll bar on the right, and see that there's a little bit of space left underneath. 您还可以查看右侧的滚动条,并在其下方留出一些空间。

screenshot2

In the above screenshot I manually scrolled down to the bottom, using the scroll bar on the right; 在上面的屏幕截图中,我使用右侧的滚动条手动向下滚动到底部; revealing the before hidden text. 揭示之前隐藏的文字。

Is there a way to make sure that the RichTextBox automatically gets scrolled to the very end, every time? 有没有一种方法可以确保RichTextBox每次都自动滚动到末尾?

This was adapted from this answer and solved the issue with the last line being cut off sometimes. 这是根据此答案改编而成的,解决了最后一条线有时被切断的问题。

I extended the answer to work as a extension method on TextBoxBase so that it can work for both TextBox and RichTextBox . 我扩展了答案,使其可以作为TextBoxBase上的扩展方法使用,以便它可以同时用于TextBoxRichTextBox

Usage: 用法:

rtb_outputWindow.ScrollToBottom();

Implementation: 执行:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM