How do I scroll a RichTextBox to the bottom?

↘锁芯ラ 提交于 2019-11-29 23:26:13

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();
DrWu

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

In WPF you can use ScrollToEnd:

richTextBox.AppendText(text);  
richTextBox.ScrollToEnd();

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

There is no need for:

richTextBox.SelectionStart = richTextBox.Text.Length;

This does the trick:

richTextBox.ScrollToCaret();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!