c# - 防止在 RichTextBox 中自动滚动

标签 c# winforms richtextbox

我有一个使用 RichTextBox 控件实现的只读数据记录窗口。我希望能够禁用当用户单击控件时发生的自动滚动,以便用户可以选择特定的日志进行复制/粘贴操作或其他操作。但是,只要用户在 RichTextBox 中单击,它就会自动滚动到底部,这让这变得很困难。

有人知道覆盖此行为的方法吗?

谢谢!

最佳答案

如果选择未隐藏,RichTextBox 控件会自动滚动到当前选择。 RichTextBox.AppendText() 除了追加文本外,还会修改当前选择,因此会间接触发“自动滚动”行为。请注意,如果 RichTextBox.HideSelection 设置为 true,则当控件未处于焦点时,选择将被隐藏;这解释了您描述的行为,其中仅当用户单击控件时才会发生自动滚动。 (从而使其成为焦点) 为防止这种情况,您需要在附加文本时执行以下操作:

  1. 备份初始选择
  2. 取消对控件的关注
  3. 隐藏选择(通过 Windows 消息)
  4. 附加文本
  5. 恢复初始选择
  6. 取消隐藏选择
  7. 重新调整控制

您可能还想检查所选内容是否已在文本末尾,如果是,则允许自动滚动行为 - 这实质上模拟了 Visual Studio 的输出窗口的行为。例如:

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
    const int WM_USER = 0x400;
    const int EM_HIDESELECTION = WM_USER + 63;

    void OnAppend(string text)
    {
        bool focused = richTextBox1.Focused;
        //backup initial selection
        int selection = richTextBox1.SelectionStart;
        int length = richTextBox1.SelectionLength;
        //allow autoscroll if selection is at end of text
        bool autoscroll = (selection==richTextBox1.Text.Length);

        if (!autoscroll)
        {
            //shift focus from RichTextBox to some other control
            if (focused) textBox1.Focus();
            //hide selection
            SendMessage(richTextBox1.Handle, EM_HIDESELECTION, 1, 0);
        }

        richTextBox1.AppendText(text);

        if (!autoscroll)
        {
            //restore initial selection
            richTextBox1.SelectionStart = selection;
            richTextBox1.SelectionLength = length;
            //unhide selection
            SendMessage(richTextBox1.Handle, EM_HIDESELECTION, 0, 0);
            //restore focus to RichTextBox
            if(focused) richTextBox1.Focus();
        }
    }

关于c# - 防止在 RichTextBox 中自动滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/626988/

相关文章:

c# - DataGridViewColumn 初始排序方向

C# WinForms 读取 XML 文件 - 仅特定节点

c# - 如何在 WinForms 中执行上下文帮助 ("what is this?"按钮)?

c# - RichTextBox最新行

c# - 同步两个 RichTextBox 的滚动位置?

c# - 如何以编程方式添加 RollingFlatFileTraceListenerData

c# - Blazor 选定 Row 参数传递

c# - 如何在 Entity Framework 中创建多对多映射?

c# - 如何结合 TaskCompletionSource 和 CancellationTokenSource?

c# - Richtextbox 在新文本前加上颜色