C# Preventing RichTextBox from scrolling/jumping to top

≡放荡痞女 提交于 2019-12-05 20:51:49
 console.Text += "\r\n" + line;

That does not do what you think it does. it is an assignment, it completely replaces the Text property. The += operator is convenient syntax sugar but the actual code that executes is

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

RichTextBox makes no effort to compare the old text with the new text to look for a possible match that could keep the caret position in the same place. It thus moves the caret back to the first line in the text. Which in turn causes it to scroll back. Jump.

You definitely want to avoid this kind of code, it is very expensive. And unpleasant if you made any effort to format the text, you'll lose the formatting. Instead favor the AppendText() method to append text and the SelectionText property to insert text (after changing the SelectionStart property). With the benefit of not just speed but no scrolling either.

After this:

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

just add this two lines:

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

Happy coding

Then, if I got you correctly, you should try this:

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

When I try it, it works like you want it to.

I had to achieve something similar, so I wanted to share...

When:

  • Focused by user: no scroll
  • Not focused by user: scroll to bottom

I took Hans Passant's advice about using AppendText() and the SelectionStart property. Here is how my code looks like:

int caretPosition = myTextBox.SelectionStart;

myTextBox.AppendText("The text being appended \r\n");

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