5

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?

truthseeker
  • 1,220
  • 4
  • 25
  • 58
  • It sounds a little strange because going to the end should be done explicitly somewhere. Are you sure the appending code isn't going to set the selection to the end itself ? – Felice Pollano Feb 07 '11 at 10:07
  • No, just AppendText("text"), AppendText("\t"), Appendtext("\n") – truthseeker Feb 07 '11 at 10:29
  • I found interesting thing. Autoscroll does happen only when the text area has focus. After clicking into text area things go wrong. If I do not click into it, I can scroll messages with scrollbar simultaneously with new messages being added and the text is not jumping. – truthseeker Feb 07 '11 at 12:38
  • See [Prevent AutoScrolling in C# RichTextBox](http://stackoverflow.com/questions/626988/prevent-autoscrolling-in-c-richtextbox), which describes the same problem. – SytS Apr 18 '11 at 16:52

2 Answers2

7

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;
Vijay Sirigiri
  • 4,653
  • 29
  • 31
0

You may try tb_logs.SelectionLength = 1; along with SelectionStart. This will make 1 char selected from your Current Position.

Not Tried it...But may work

Protean
  • 116
  • 7