0

I want to keep a certain number of lines in the richtextbox, so I did the following:

    private void txt_Log_TextChanged(object sender, EventArgs e)
    {
        int max_lines = 200;
        if (txt_Log.Lines.Length > max_lines)
        {
            string[] newLines = new string[max_lines];
            Array.Copy(txt_Log.Lines, 1, newLines, 0, max_lines);
            txt_Log.Lines = newLines;
        }
        txt_Log.SelectionStart = txt_Log.Text.Length;
        txt_Log.ScrollToCaret();
    }

But when running my Richtextnbox blinks continuously, so how should I make this smooth ?

JimmyN
  • 579
  • 4
  • 16
  • 1
    I believe when you update a value of the `txt_Log.Lines` property, the `txt_Log_TextChanged` event fires again. Could you debug the code to verify it? – Dmitry Aug 28 '17 at 16:41

2 Answers2

1

One option would be to unhook the listener, perform the update, then re-hook the listener upon exiting the function.

private void txt_Log_TextChanged(object sender, EventArgs e)
{
    txt_Log.TextChanged -= this.txt_Log_TextChanged;

    //make you're updates here...

    txt_Log.TextChanged += this.txt_Log_TextChanged;
}
Ryan Naccarato
  • 674
  • 8
  • 12
0

When you update a value of the txt_Log.Lines property, the txt_Log_TextChanged event fires again.

You could use a bool variable to stop it:

private bool updatingTheText;

private void txt_Log_TextChanged(object sender, EventArgs e)
{
    if (updatingTheText)
        return;

    const int max_lines = 200;
    if (txt_Log.Lines.Length > max_lines)
    {
        string[] newLines = new string[max_lines];
        Array.Copy(txt_Log.Lines, 1, newLines, 0, max_lines);
        updatingTheText = true;  // Disable TextChanged event handler
        txt_Log.Lines = newLines;
        updatingTheText = false; // Enable TextChanged event handler
    }
    txt_Log.SelectionStart = txt_Log.Text.Length;
    txt_Log.ScrollToCaret();
}
Dmitry
  • 13,797
  • 6
  • 32
  • 48
  • You were right, the textchange event was repeatedly called, I tried your suggestion, it was lessened, but still flashing a lot. – JimmyN Aug 28 '17 at 16:59
  • @jimbo You could use a workaround from these topics: [stackoverflow.com/questions/9418024](https://stackoverflow.com/questions/9418024/richtextbox-beginupdate-endupdate-extension-methods-not-working) and [social.msdn.microsoft.com](https://social.msdn.microsoft.com/Forums/windows/en-US/a6abf4e1-e502-4988-a239-a082afedf4a7/anti-flicker-in-richtextbox-c?forum=winforms) – Dmitry Aug 28 '17 at 17:16