How do I scroll a RichTextBox to the bottom?

守給你的承諾、 提交于 2019-11-30 10:52:22

问题


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.


回答1:


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



回答2:


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



回答3:


In WPF you can use ScrollToEnd:

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



回答4:


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



回答5:


There is no need for:

richTextBox.SelectionStart = richTextBox.Text.Length;

This does the trick:

richTextBox.ScrollToCaret();


来源:https://stackoverflow.com/questions/895470/how-do-i-scroll-a-richtextbox-to-the-bottom

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