Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

c# - Disabling RichTextBox autoscroll

I am using RichTextBox control for displaying application logs. I am updating control once a second with a few calls of RichTextBox::AppendText method. What is really annoying for me is that cursor keeps scrolling to the last line of text. Its very uncomfortable in situation when user needs to analyze logs that are at the beginning. I have tried following solution to my problem:

int pos = tb_logs.SelectionStart;
tb_logs.AppendText("log message");
tb_logs.SelectionStart = pos;

This does not go to the core of problem because control is being periodically redrawed which is very distracting. Is there some cleaner solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your issue is with the "Vertical Scroll" scrolling down when you are adding the Log text, but you would want it to be on top all the time:

you have to add event handlers to VScroll, TextChanged events and in the event handler set the scroll to top

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);
}

You could do the same with horizontal scroll bar too. Replace WM_VSCROLL with WM_HSCROLL and SB_TOP with SB_LEFT

private const UInt32 WM_HSCROLL = 0x0114;
private const UInt32 SB_LEFT = 0x06;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...