Avoid TextBox flickering while appending text

898 views Asked by At

I have a WindowsForm MDI application with a textbox where text stream coming from a serial port is displayed.

This text box by default auto-scroll to the end of the textbox each time I append text to it.

But I added an option to stop autoscroll, here is the code:

namespace MyNs
{
  public class MyForm
  {
    void updateTextbox_timerTick(object sender, EventArgs e)
    {
      int cursorPos = textbox.SelectionStart;
      int selectSize = textbox.SelectionLength;

      if(!autoscroll)
        textbox.SuspendDrawing();

      lock(bufferLock)
      {
        textbox.AppendText(buffer.ToString());
        buffer.Clear();
      }

      if(autoscroll)
      {
        textbox.Select(textbox.Text.Length, 0);
        textbox.ScrollToCaret();
      }
      else
      {
        textbox.Select(cursorPos, selectSize);
        textbox.ResumeDrawing();
      }
    }
  }

  public static class Utils
  {
        [DllImport("user32.dll")]
        private static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);

        private const int WM_SETREDRAW = 11;

        public static void SuspendDrawing(this Control parent)
        {
            SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
        }

        public static void ResumeDrawing(this Control parent)
        {
            SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
        }
  }
}

Using my method ResumeDrawing and SuspendDrawing let the textbox stay at his position while appending. But this also add flickering problems. Do you know how I can resolve these problems ?

Thanks for you help :)

1

There are 1 answers

0
AMDG On BEST ANSWER

Thanks to this question : Flicker free TextBox

The solution is to enable WS_EX_COMPOSITED params on the form or the control.

To do so you just have to add this to your form or derived control class:

private const int WS_EX_COMPOSITED = 0x02000000; 
protected override CreateParams CreateParams {
  get {
    CreateParams cp = base.CreateParams;
    cp.ExStyle |= WS_EX_COMPOSITED;
    return cp;
  }
} 

Don't forget to also enable DoubleBuffering.