AdSense

Friday, 14 June 2013

C# Windows Forms - Draw double buffered

(Deutsche Version) To draw everything in Panzerkampf, I used Windows Forms. A redraw event is deleting everything and then re-painting everything. This causes a very annoying flickering. To avoid this, everything is painted into an image and then the image is painted on the actual view - which will not be cleared because the image covers everything. This solves the flickering problem. Here is the code:

void drawDoubleBufBmp()
{
    Bitmap localBitmap = new Bitmap(settings.SizeX, settings.SizeY);
    using (Graphics gx = Graphics.FromImage(localBitmap))
    {
        gx.DrawDrawString("Panz.....");
    }
    lock (BmpLock)
    {
        doubleBufBmp = localBitmap;
    }
}


private Bitmap doubleBufBmp = new Bitmap(settings.SizeX, settings.SizeY);
private object BmpLock = new object();
protected override void OnPaint(PaintEventArgs e)
{
    lock (BmpLock)
    {
        g.DrawImage(doubleBufBmp, 0, 0);
    }
}

protected override void OnPaintBackground(PaintEventArgs e)
{}


I had to overwrite OnPaintBackground because this was causing the flickering. In the OnPaint function, I simply draw the complete doubleBufBmp in the Window. drawDoubleBufBmp() is called by a thread every 10 milliseconds, which then calls this.Invalidate(); which causes the OnPaint function to be called.

No comments:

Post a Comment