Use LockWindowUpdate to get flicker-free RichTextBox update

Very simple, but I had to dig around to find it so I might as well share it here. I do lots of updates to a RichTextBox while colorparsing some code, and I didn't like the flickering.

Since there is no BeginUpdate() or similar, I had to use Win32 api from user32.dll:

      [DllImport("user32.dll")]

      public static extern bool LockWindowUpdate(IntPtr hWndLock);

To use it just:

try

{

      LockWindowUpdate(richTextBox1.Handle);

      //change colors and stuff in the RichTextBox

}

finally

{

      LockWindowUpdate(IntPtr.Zero);

}

 

UPDATE: I got a tip fom Kevin Westhead to use SendMessage() with WM_SETREDRAW instead:

 

I think it's better to use SendMessage with WM_SETREDRAW to enable/disable drawing on a window since LockWindowUpdate can only be applied to one window. This means that you might not be able to lock your window if someone else has already locked a window, or someone else could unlock your window without you knowing.

So if you prefer this alternative, please do like this:

 

private const int WM_SETREDRAW      = 0x000B;

private const int WM_USER           = 0x400;

private const int EM_GETEVENTMASK   = (WM_USER + 59);

private const int EM_SETEVENTMASK   = (WM_USER + 69);

 

[DllImport("user32", CharSet = CharSet.Auto)]

private extern static IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam);

 

IntPtr eventMask = IntPtr.Zero;

try

{

      // Stop redrawing:

      SendMessage(richTextBox1.Handle, WM_SETREDRAW, 0, IntPtr.Zero);

      // Stop sending of events:

      eventMask = SendMessage(richTextBox1.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);

 

      // change colors and stuff in the RichTextBox

}

finally

{

      // turn on events

      SendMessage(richTextBox1.Handle, EM_SETEVENTMASK, 0, eventMask);

      // turn on redrawing

      SendMessage(richTextBox1.Handle, WM_SETREDRAW, 1, IntPtr.Zero);

}

 

Thanks Kevin!

3 Comments

  • I think it's better to use SendMessage with WM_SETREDRAW to enable/disable drawing on a window since LockWindowUpdate can only be applied to one window. This means that you might not be able to lock your window if someone else has already locked a window, or someone else could unlock your window without you knowing.

  • Thx a lot for your info.



    Works great for a Panel with mutiple TextBoxes...

  • I'm new to C#, but I'm a veteran VB( and now VB.NET) programmer, but does SuspendLayout() and ResumeLayout() not work in C#?

Comments have been disabled for this content.