Search code examples
c#winformstextboxflickerdoublebuffered

How to prevent TextBox flickering?


I try to prevent TextBox flickering with no success so far.
The TextBox is multiline readonly.

This code run a few times per second. The text has about 10k characters.

int ss = txt.SelectionStart;
int sl = txt.SelectionLength;
txt.Text = s;
txt.SelectionStart = ss;
txt.SelectionLength = sl;

Resarching the problem gives me the following possible solutions
- but none of them worked.

1) LockWindowUpdate

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool LockWindowUpdate(IntPtr hWndLock);

//...

LockWindowUpdate(txt.Handle);
txt.Text = someText;
LockWindowUpdate(IntPtr.Zero);

2) SetStyle

this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);

3) SuspendLayout / ResumeLayout (guess it has nothing to do with paint - but just a try)

txt.SuspendLayout();
txt.Text = s;
txt.ResumeLayout();

Solution

  • It turns out that CreateParams of the parent form has to use the WS_EX_COMPOSITED flag:

        protected override CreateParams CreateParams {
            get {
                new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;   // WS_EX_COMPOSITED
                return cp;
            }
        }