1

I create a richtexbox for realtime log. If length of richtexbox is too large, I 'll remove old data ( such as 1/3 current data ).

 Content.Invoke(new EventHandler(delegate
            {
               Content.AppendText(msg);   
                if(Content.Text.Length >100000)
                {
                    Content.Select(0, 50000);
                    Content.SelectedText = "";
                }
            }));

My problem is whenever I remove data, scrollbar go up ( select text ) and go down ( append new text). Is there anyway to prevent scrollbar going up ?

Green
  • 451
  • 1
  • 6
  • 11
  • If I have read your question correctly his article may help: http://stackoverflow.com/questions/6695607/prevent-richtextbox-from-auto-scrolling – Fred May 07 '14 at 07:27
  • possible duplicate of [Disabling RichTextBox autoscroll](http://stackoverflow.com/questions/4919969/disabling-richtextbox-autoscroll) – Kilazur May 07 '14 at 07:27
  • I dont want to prevent it scrolling to the last line of text, I just want to prevent it scrolling to the top when I remove texts in top of richtexbox ( keep scrolling to the last line ) – Green May 07 '14 at 07:31
  • Maybe `SuspendLayout()` and `ResumeLayout()` before and after your changes will help? Also I don't see you storing and recalculating the SelectionStart/End!? – TaW May 07 '14 at 07:56
  • scrollbar still go up when I remove text in top. Btw, why I need storing and recalculating the SelectionStart/End!? – Green May 07 '14 at 08:10

1 Answers1

1

I tried this in a timer and it looks fine to me. Obviously the scrollbar grows when you remove text, but that is supposed to happen..

    private void timer1_Tick(object sender, EventArgs e)
    {
        richTextBox1.SuspendLayout();
        richTextBox1.AppendText( richTextBox1.Text.Length.ToString() +
           "  some random text of no consequence.....\n");
        if (richTextBox1.Text.Length > 10000)
        {
            richTextBox1.Select(0, 2000);
            richTextBox1.SelectedText = "";
        }

        richTextBox1.SelectionStart = richTextBox1.Text.Length;
        richTextBox1.SelectionLength = 0;
        richTextBox1.ScrollToCaret();
        richTextBox1.ResumeLayout();
    }

I assume that you always want the end of the RTB visible, so you have to bring the caret to the end and in sight. If you don't do that the caret will be at the top after the removal of the top portion of the text.. No need to store the caret position, unless you want it to stay at some other position, maybe because the user has put it there..? In that case however you must act accordingly and calculate the correct position!

TaW
  • 53,122
  • 8
  • 69
  • 111