VB.NET double buffering

pluke picture pluke · Dec 13, 2011 · Viewed 8.5k times · Source

I’ve been trying to get the double buffer function working in VB.NET GDI+ for a space invaders game using the following command

Public Sub New()
      …
    Me.SetStyle(ControlStyles.DoubleBuffer, True)
End Sub

But because I am using a separate draw routine attached to a class it doesn’t seem to work:

Class alien
   …
   Public Sub draw(ByVal palette)
      Dim image As New Drawing.Bitmap("E:\alien.gif")
      palette.DrawImage(image, loc.X, loc.Y, width, height)
   End Sub
End class

I call this routine from a timer on the main form:

Private Sub TmrAlien_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)     Handles TmrAlien.Tick
    Dim palette As Drawing.Graphics = Me.CreateGraphics

    dave.draw(palette)
    Invalidate()
End sub

The aliens draw correctly but the images are very stuttery and double buffering doesn’t seem to work.

Any ideas

Answer

Hans Passant picture Hans Passant · Dec 13, 2011

The problem is in your Tick event handler. Drawing with the Graphics object returned by CreateGraphics() is never double-buffered. Calling Invalidate() is what causes the flicker, it forces the form to repaint itself and that will overwrite what you painted in the draw() method. You'll see the alien for just a very brief moment.

Fix it like this:

Public Sub New()
      …
    Me.DoubleBuffered = True
End Sub

Private Sub TmrAlien_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)     Handles TmrAlien.Tick
    '' Change dave.Loc
    ''...
    Invalidate()
End sub

Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
    dave.draw(e.Graphics)
    MyBase.OnPaint(e)
End Sub