【问题标题】:C# Preventing RichTextBox from scrolling/jumping to topC# 防止 RichTextBox 滚动/跳到顶部
【发布时间】:2012-09-29 00:27:24
【问题描述】:

似乎在使用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 并覆盖效果不佳的滚动功能。

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

它不应该到顶部,也不应该到底部,当然也不应该到当前选择,而应该停留在当前位置。

【问题讨论】:

    标签: c# scroll richtextbox


    【解决方案1】:

    我必须实现类似的目标,所以我想分享...

    时间:

    • 以用户为中心:无滚动
    • 用户未关注:滚动到底部

    我接受了 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();
    }
    

    【讨论】:

    • 这行得通,但由于 idk 问题,它有几次跳跃。
    【解决方案2】:
     console.Text += "\r\n" + line;
    

    这并不像你认为的那样。它是一个 assignment,它完全取代了 Text 属性。 += 运算符是方便的语法糖,但实际执行的代码是

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

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

    你肯定想避免这种代码,它非常昂贵。如果你努力格式化文本,你会失去格式。而是倾向于 AppendText() 方法来追加文本和 SelectionText 属性来插入文本(在更改 SelectionStart 属性之后)。不仅速度快,而且无需滚动。

    【讨论】:

    • 我明白了,如何防止 AppendText() 滚动? AppendText() 让我再次滚动到底部。而且由于除了选择之外没有其他方法可以获取用户的当前位置,因此我无法向后滚动,除非首先阻止它滚动。
    • @user1137183:我没有看到这个问题。富文本框中的选择开始是光标位置。只是事先保存,写入后再恢复?
    【解决方案3】:

    那么,如果我没听错的话,你应该试试这个:

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

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

    【讨论】:

      【解决方案4】:

      之后:

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

      只需添加这两行:

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

      愉快的编码

      【讨论】:

      • 如果聚焦和不聚焦,这实际上会滚动到底部。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      • 1970-01-01
      相关资源
      最近更新 更多