2012-10-08 260 views
3

看来,使用System.Windows.Forms.RichTextBox时,您可以使用textbox.AppendText()textbox.Text = ""向文本框中添加文本。C#防止RichTextBox滚动/跳到顶部

AppendText将滚动到底部并直接添加文本不会滚动,但会在用户关注文本框时跳转到顶部。

这里是我的功能:

// 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和重载滚动功能,没有工作这么好。

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

它不应该走到最前面,也不会走到最前面,当然也不会当前选择,而是保持目前的状态。

回答

1

在此之后:

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

只需添加这两条线:

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

快乐编码

+0

这实际上会滚动到底部,如果集中并且不重点。 – user1137183

0

然后,如果我没有得到你,你应该试试这个:

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

当我尝试一下,它就像你想要的那样工作。

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

这并不符合您的想法。它是赋值,它完全替换了Text属性。 + =操作是方便的语法糖,但执行是

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

RichTextBox中没有努力比较旧文本与新文本以寻找可能的匹配,可以保持在相同的插入位置的实际代码地点。它因此将插入符号移回文本中的第一行。这反过来导致它回滚。跳。

你一定要避免这种代码,它是非常昂贵的。如果您尝试对文本进行格式设置,您会感到不愉快,您将失去格式。而是赞成AppendText()方法追加文本,SelectionText属性插入文本(在更改SelectionStart属性之后)。不仅速度的好处而且不滚动。

+1

我明白了,我该如何防止AppendText()滚动? AppendText()让我再次滚动到底部。由于除了选择之外无法获取用户的当前位置,因此我无法向前滚动,除非阻止它首先滚动。 – user1137183

+0

@ user1137183:我看不到问题。在富文本框中选择开始是光标位置。提前保存并在写入后恢复它? – Nyerguds

0

我不得不来实现类似的东西,所以我想分享...

当:

  • 用户聚焦:没有滚动
  • 没有聚焦用户:滚动到底

我拿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(); 
} 
相关问题