C# 如何将 RichTextBox 滚动到底部?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/895470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I scroll a RichTextBox to the bottom?
提问by Very Very Cherry
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.
我需要能够将 RichTextBox 滚动到底部,即使我没有附加文本。我知道我可以附加文本,然后使用它来设置选择开始。但是,出于视觉原因,我想确保它位于底部,因此我没有添加任何文本。
采纳答案by Brandon
You could try setting the SelectionStart property to the length of the text and then call the ScrollToCaret method.
您可以尝试将 SelectionStart 属性设置为文本的长度,然后调用 ScrollToCaret 方法。
richTextBox.SelectionStart = richTextBox.Text.Length;
richTextBox.ScrollToCaret();
回答by mxgg250
In WPF you can use ScrollToEnd:
在 WPF 中,您可以使用 ScrollToEnd:
richTextBox.AppendText(text);
richTextBox.ScrollToEnd();
回答by Ben Richards
There is no need for:
不需要:
richTextBox.SelectionStart = richTextBox.Text.Length;
This does the trick:
这是诀窍:
richTextBox.ScrollToCaret();
回答by 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.
RichTextBox
如果它有焦点并且您AppendText
用来添加信息,它将保持滚动到最后。如果您设置HideSelection
为 false,它将在失去焦点时保持其选择并保持自动滚动。
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%.
我设计了一个使用以下方法的日志查看器 GUI。它使用了一个完整的核心跟上。删除此代码并将HideSelection
CPU 使用率设置为 false 使 CPU 使用率降至 1-2%。
//Don't use this!
richTextBox.AppendText(text);
richTextBox.ScrollToEnd();
回答by agileDev
Code should be written in the rich text box's TextChanged event like :
代码应该写在富文本框的 TextChanged 事件中,如:
private void richTextBox_TextChanged(object sender, EventArgs e) {
richTextBox.SelectionStart = richTextBox.Text.Length;
richTextBox.ScrollToCaret();
}