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

时间:2012-10-08 18:02:35

标签: c# scroll richtextbox

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

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并覆盖那些效果不佳的滚动功能。

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

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

4 个答案:

答案 0 :(得分:4)

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

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

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

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

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

答案 1 :(得分:1)

之后:

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

只需添加以下两行:

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

快乐编码

答案 2 :(得分:0)

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

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

当我尝试它时,它就像你想要它一样。

答案 3 :(得分: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();
}