Double Buffering a Panel

I tried all sorts of combinations of using the EnableDoubleBuffering() method you provided with the sample code, but at best there was still a little flicker on the panel. What I ended up doing was doublebuffering the panel by hand. My actual code is filled with the fish logic, so it would probably be best to just explain the changes I made to do the double buffering.

These are all changes in the PanelSpecial class It requires two more class variables:

  Bitmap offScreenBmp;
  Graphics offScreenDC;
which are initialized in the constructor:
  offScreenBmp = new Bitmap(this.Width, this.Height);
  offScreenDC = Graphics.FromImage(offScreenBmp);
Note that this.Width and this.Height aren't necessarily set at the time of construction, so you have to handle the resize event and reinitialize this backbuffer:
  private void PanelSpecial_Resize(object sender, EventArgs e)
  {
     offScreenBmp = new Bitmap(this.Width, this.Height);
     offScreenDC = Graphics.FromImage(offScreenBmp);
  }
Now every time paint is called, the drawing is done to this invisible Graphics object, then the associated Bitmap is drawn to the panel Graphics:
  offScreenDC.FillRectangle(Brushes.AliceBlue, 0, 0, this.Width, this.Height);
  DrawAll(offScreenDC);
  clientDC.DrawImage(offScreenBmp, 0, 0);
In this case, all my drawing is handled by the DrawAll method.

I'm sure there is a way to get SetStyle to do the double buffering automatically, but there are a lot of variables that can make it go very wrong, or as is my experience with it. - Dennis Lipovsky, Nov. 2005
Visitors:    Hit Counter