Double buffering in .NET

Ever wondered how to double buffer with a Graphics object so your GDI+ based game/control doesn't flicker annoyingly? Me too.  There's probably a built in method that's easier, but this is how I managed to get it to work smoothly, it's nice and simple and allows you to draw anywhere that offers up the normal CreateGraphics method.

First, set up a bitmap to act as your backbuffer:


Bitmap BackBuffer = new Bitmap(this.ClientSize.Width,this.ClientSize.Height);
Graphics DrawingArea = Graphics.FromImage(BackBuffer);


Dim BackBuffer As New Bitmap(Me.ClientSize.Width,Me.ClientSize.Height)
Dim DrawingArea As Graphics = Graphics.FromImage(BackBuffer)

Next, you want to draw to your graphics object as normal, so DrawingArea.Clear(Color.Black) and such.

Once you've completed drawing the object that you want to smoothly move, simply draw the pre-rendered bitmap over the top of the Graphics object you want to update:


Graphics Viewable = Me.CreateGraphics();
Viewable.DrawImageUnscaled(BackBuffer, 0, 0);


Dim Viewable As Graphics = Me.CreateGraphics()
Viewable.DrawImageUnscaled(BackBuffer, 0, 0)

You can also use other techniques to increase the performance, such as reusing the backbuffer by defining it in the class you're using it in - this means .NET won't need to recreate it repeatedly.

Updated: I have just noticed there's a Control.SetStyle method that automates double buffering in many situations where you are drawing to a control - place this in the forms initialisation:

this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);

You might also like...


Simon Soanes


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Anyone who considers arithmetic methods of producing random digits is, of course, in a state of sin.” - John von Neumann