How do I scroll a RichTextBox to the bottom?

2019-02-01 19:58发布

I need to be able to scroll a RichTextBox to the bottom, even when I am not appending text. I know I can append text, and then use that to set the selection start. However I want to ensure it is at the bottom for visual reasons, so I am not adding any text.

5条回答
时光不老,我们不散
2楼-- · 2019-02-01 20:31

Code should be written in the rich text box's TextChanged event like :

private void richTextBox_TextChanged(object sender, EventArgs e) {
       richTextBox.SelectionStart = richTextBox.Text.Length;
       richTextBox.ScrollToCaret();
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-02-01 20:36

In WPF you can use ScrollToEnd:

richTextBox.AppendText(text);  
richTextBox.ScrollToEnd();
查看更多
该账号已被封号
4楼-- · 2019-02-01 20:41

You could try setting the SelectionStart property to the length of the text and then call the ScrollToCaret method.

richTextBox.SelectionStart = richTextBox.Text.Length;
richTextBox.ScrollToCaret();
查看更多
对你真心纯属浪费
5楼-- · 2019-02-01 20:49

The RichTextBox will stay scrolled to the end if it has focus and you use AppendText to add the information. If you set HideSelection to false it will keep its selection when it loses focus and stay auto-scrolled.

I designed a Log Viewer GUI that used the method below. It used up to a full core keeping up. Getting rid of this code and setting HideSelection to false got the CPU usage down to 1-2%.

//Don't use this!
richTextBox.AppendText(text);  
richTextBox.ScrollToEnd();
查看更多
祖国的老花朵
6楼-- · 2019-02-01 20:50

There is no need for:

richTextBox.SelectionStart = richTextBox.Text.Length;

This does the trick:

richTextBox.ScrollToCaret();
查看更多
登录 后发表回答