Reputation:
I have a RichTextBox which I want to automatically scroll to the end of the text, when new text gets added.
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:
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:
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.
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?
Upvotes: 4
Views: 4037
Reputation: 3611
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
.
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);
}
}
Upvotes: 3