禁用RichTextBox自动滚动

tru*_*ker 5 c# refresh richtextbox autoscroll

我正在使用RichTextBox控件来显示应用程序日志.我通过几次调用RichTextBox :: AppendText方法每秒更新一次控制.对我来说真正烦人的是光标一直滚动到文本的最后一行.当用户需要分析开头的日志时,它非常不舒服.我试过以下解决方案来解决我的问题:

int pos = tb_logs.SelectionStart;
tb_logs.AppendText("log message");
tb_logs.SelectionStart = pos;
Run Code Online (Sandbox Code Playgroud)

这不是问题的核心,因为定期重新绘制控制,这非常分散注意力.有一些更清洁的解决方案?

Vij*_*iri 7

如果您在添加日志文本时向下滚动"垂直滚动"问题,但您希望它始终位于顶部:

您必须向VScroll,TextChanged事件添加事件处理程序,并在事件处理程序中将滚动设置为顶部

richTextBox1.VScroll += HandleRichTextBoxAdjustScroll;
richTextBox1.TextChanged += HandleRichTextBoxAdjustScroll;

private const UInt32 SB_TOP = 0x6;
private const UInt32 WM_VSCROLL = 0x115;

[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
private static extern bool PostMessage(IntPtr hWnd, UInt32 Msg,
    IntPtr wParam, IntPtr lParam);

private void HandleRichTextBoxAdjustScroll(Object sender,
    EventArgs e)
{
    PostMessage(handle, WM_VSCROLL, (IntPtr)SB_TOP, IntPtr.Zero);
}
Run Code Online (Sandbox Code Playgroud)

你也可以用水平滚动条做同样的事情.用WM_HSCROLL替换WM_VSCROLL,用SB_LEFT替换SB_TOP

private const UInt32 WM_HSCROLL = 0x0114;
private const UInt32 SB_LEFT = 0x06;
Run Code Online (Sandbox Code Playgroud)