Library code snippets

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:

C#

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

VB.NET

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:

C#

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

VB.NET

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);
this.UpdateStyles();

Comments

  1. 02 Jun 2008 at 15:55

     As you have done this in .NET, do you have any recommendations for the best way to do the same in VB6?  Thanks in advance.

  2. 22 Sep 2006 at 07:26

    Simply awesome way to do double buffering. I am creating my first windows drawing application using double buffering that you suggested and I absolutely love it! so simple and yet so effective ! Thanks a lot.

  3. 01 Jan 1999 at 00:00

    This thread is for discussions of Double buffering in .NET.

Leave a comment

Sign in or Join us (it's free).

Simon Soanes

Related discussion

Related podcasts

  • More jQuery in ASP.NET

    In this episode Chris Brandsma, Rick Strahl, Dave Ward, Bertrand Le Roy, and Scott Koon conclude their discussion of Microsoft's jQuery in ASP.NET announcement1.This episode of the Alt.NET Podcast is brought to you by LLBLGen Pro, the most mature O/R mapper and code generator out there.Are ...

Events coming up

  • Dec 9

    GL.net Group Meeting - December 2009

    Gloucester, United Kingdom

    The beginning of this year holiday season will belong to mocks. Ronnie and Stephen will take us for a tour around exciting world of unit testing.

We'd love to hear what you think! Submit ideas or give us feedback