Use double buffering to prevent flicker when drawing in C#

The example Draw a colored butterfly curve in C# shows how to draw a colorful butterfly curve. Without mentioning it, I used double buffering in that program to avoid flickering while drawing. To use double buffering, simply set a form’s DoubleBuffer property to true.

When you use double buffering, the system allocates a separate piece of memory to hold the form’s image. When the Paint event handler draws on the form, the system draws on this in-memory image. When it is finished, the system displays the form’s image all at once. If the drawing is complicated, as in this example, that prevents the user from seeing the flickering image as the program draws it.

When you check this example’s Double Buffer box, the program enables or disables double buffering and then redraws. You can also click the Redraw button to force a redraw.

The following code shows how the check box turns double buffering on and off.

// Turn double buffering on or off and redraw.
private void chkDoubleBuffer_CheckedChanged(
    object sender, EventArgs e)
    this.DoubleBuffered = chkDoubleBuffer.Checked;

When double buffering is off, you should see the flicker. When double buffering is on, the redraw happens so smoothly that you probably won’t notice anything. Resize the form to force a redraw that is more noticeable.

Double buffering does take some extra memory, so you should only use it when you are drawing enough to make the flicker visible.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in graphics, image processing and tagged , , , , , , , , , , . Bookmark the permalink.

One Response to Use double buffering to prevent flicker when drawing in C#

  1. Pingback: Use double buffering to prevent flicker in a PictureBoxC# Helper

Leave a Reply

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