Scrolling a C# RichTextbox when adding text
The need for an autoscroll property…
Tons of applications are using the .NET RichTextBox for outputting status information. You have a RichTextBox that you just keep on adding text to. This is all very simple, but when the box is completely filled with text, further text added will no longer be visible, since the RichTextBox does not scroll along with the text. Wouldn’t it be nice if you could make it scroll along with the text automatically.
Well… You can.
Use the TextChanged event
Whenever you add (or change in any way) text to the RichTextBox the TextChanged event will fire immediately after the text has changed. Just double-click on the TextChanged event in the RichTextBox’ event list to add an event handler.
Now modify the code of the event handler to look like this:
private void richTextBox_TextChanged(object sender, EventArgs e) { richTextBox.SelectionStart = richTextBox.Text.Length; richTextBox.ScrollToCaret(); }
This code uses the ScrollToCaret function to do the actual scrolling. The function will adjust the scroll of the box, so that the “caret” is visible (think of the caret as the blinking cursor). This of course requires that the caret is placed somewhere meaningfull. This is done by setting the SelectionStart property to the last character in the box. The result is that whenever the text in the RichTextBox changes the box will scroll to the very bottom.
While this method is perfect for your basic status information box, where information is always added to the bottom, it may not always be the proper solution. This method will reset any selection the user has made in the RichTextBox, so if you need to copy text out of the box and the text changes very often this is not really the way to go.
On the other hand it is a very simple and safe way of implementing “autoscroll” and i have used it in a lot of applications without any problems.

May 10th, 2009 at 6:15 pm
This is a quick and dirty solution to the autoscroll problem. A more elegant solution is outlined in this post.
September 24th, 2009 at 4:37 am
Nah,
I prefer the above although do the whole call in one void
private void writeToStatusWindow(string textToBeWritten)
{
rchTxtBxSTATUS.AppendText(textToBeWritten);
rchTxtBxSTATUS.SelectionStart = rchTxtBxSTATUS.Text.Length;
rchTxtBxSTATUS.ScrollToCaret();
}
just set the max length of your rich text box if youre running tests for days or months or you will blow your memory
October 9th, 2009 at 8:29 am
The ScrollToCaret() method only works if the control has focus. It also makes text-selection difficult….
So sending a WM_VSCROLL message will often be a better solution.