Enabling Double-Buffering in .Net Controls

Interesting: rendering controls in a double-buffered fashion is available as standard in .Net, but it is not enabled by default. Double-buffering can be useful if you have a window with a lot of information on it, which is slow to redraw, and you want to reduce the visible ‘flicker’ when the form is redrawn. Double-buffering is very common in graphics-intensive applications, and is the practise of drawing graphics to an off-screen buffer, then slapping the buffer onto the screen in one big hit. The alternative is to draw the elements directly to the screen one by one, hence the visible delay if there are a lot of elements.

Traditionally (at least in my experience), double-buffering has required manually creating an off-screen canvas; explicitly drawing your controls, graphics, etc. to the off-screen canvas; and then swapping that canvas to the screen.

Anyway, cutting to the chase; double-buffering is enabled via the SetStyle method of the base control class. The technique is fully described in the documentation, but here is the guts of it (in c# syntax):

public void EnableDoubleBuffering()
{
  // Set the value of the double-buffering style bits to true.
  this.SetStyle(ControlStyles.DoubleBuffer |
      ControlStyles.UserPaint |
      ControlStyles.AllPaintingInWmPaint,
      true);
   this.UpdateStyles();
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.