C#阻止RichTextBox滚动/跳转到顶部

看来,当使用System.Windows.Forms.RichTextBox您可以使用textbox.AppendText()textbox.Text = ""将文本添加到文本框中。

AppendText将滚动到底部,直接添加文本将不会滚动,但是当用户将文本框聚焦时,它将跳转到顶部。

这是我的function:

 // Function to add a line to the textbox that gets called each time I want to add something // console = textbox public void addLine(String line) { // Invoking since this function gets accessed by another thread console.Invoke((MethodInvoker)delegate { // Check if user wants the textbox to scroll if (Settings.Default.enableScrolling) { // Only normal inserting into textbox here with AppendText() } else { // This is the part that doesn't work // When adding text directly like this the textbox will jump to the top if the textbox is focused, which is pretty annoying Console.WriteLine(line); console.Text += "\r\n" + line; } }); } 

我也尝试导入user32.dll并覆盖滚动function,这些function效果不佳。

有谁知道如何一劳永逸地停止滚动文本框?

它不应该在顶部,也不应该在底部,当然也不应该是当前的选择,而是保持目前的状态。

  console.Text += "\r\n" + line; 

这不符合你的想法。 它是一个赋值 ,它完全取代了Text属性。 + =运算符是方便的语法糖,但执行的实际代码是

  console.Text = console.Text + "\r\n" + line; 

RichTextBox不会将旧文本与新文本进行比较,以寻找可能将插入位置保持在同一位置的可能匹配。 因此它将插入符号移回文本中的第一行。 这反过来导致它向后滚动。 跳。

你肯定想避免这种代码,它非常昂贵。 如果您努力格式化文本并且不愉快,您将失去格式。 而是支持AppendText()方法追加文本和SelectionText属性来插入文本(在更改SelectionStart属性之后)。 不仅有速度而且没有滚动的好处。

在这之后:

  Console.WriteLine(line); console.Text += "\r\n" + line; 

只需添加以下两行:

 console.Select(console.Text.Length-1, 1); console.ScrollToCaret(); 

快乐的编码

然后,如果我找到你,你应该试试这个:

 Console.WriteLine(line); console.SelectionProtected = true; console.Text += "\r\n" + line; 

当我尝试它时,它的工作方式就像你想要的那样。

我必须实现类似的东西,所以我想分享……

什么时候:

  • 用户关注:无滚动
  • 用户不关注:滚动到底部

我采用了Hans Passant关于使用AppendText()和SelectionStart属性的建议。 以下是我的代码的样子:

 int caretPosition = myTextBox.SelectionStart; myTextBox.AppendText("The text being appended \r\n"); if (myTextBox.Focused) { myTextBox.Select(caretPosition, 0); myTextBox.ScrollToCaret(); }