Michael O'Dea-Jones' Blog

Double Buffering Windows Forms

I'm working on an application where the presentation is very important and I want it to look great. I am overriding the Form's OnPaint() method so that I can create a Gradient background. I thought that I had done a fantastic job until I started to resize the Form and Noticed that it was flickering. Not to be outdone I researching the issue I came across a technique called Double Buffering that made a big difference.

Double Buffering is the process whereby the Painting is done in memory first and then the result is copied to the screen. This is different from the default mode where the painting is done directly to the screen. Another contributing factor was that the Form was painting the Background and Foreground in two separate actions. These two actions can be combined to reduce flickering.

In order to configure Double Buffering you need to apply three Styles to the Control and then force the Control to apply the new styles. Here are the three Styles:

  1. ControlStyles.AllPaintingInWmPaint
    1. Ignores Background Paint messages. The Control's Background and Foreground are painted at the same time.
  2. ControlStyles.UserPaint
    1. Configures the Control to execute the OnPaint and OnPaintBackground Methods.
  3. ControlStyles.DoubleBuffer
    1. Paints the Control in memory first and then copied the result to the screen.

Invoke the Form's SetStyle() method to configure it for Double Buffering:

protected override void OnLoad(EventArgs e)

{

base.OnLoad(e);

    // Double Buffer to reduce flickering

this.SetStyle(ControlStyles.AllPaintingInWmPaint |

ControlStyles.UserPaint |

ControlStyles.DoubleBuffer, true);

this.UpdateStyles();

}

Published Wednesday, July 30, 2008 9:14 PM by michael@wardyit.com

Comments

No Comments
Anonymous comments are disabled

News

Michael is a .Net Developer who enjoys creating software and doing database work too.

Tags

No tags have been created or used yet.