Dmitry Pavlushin
Dmitry Pavlushin

Reputation: 612

Can't draw on double buffered form

In my form class I have overridden the OnPaint method

protected override void OnPaint(PaintEventArgs e)
{
    using (Graphics g = e.Graphics)
    {
        g.DrawImage(player.Sprite, new Rectangle(player.X, player.Y, 20, 20));
    }
    base.OnPaint(e);
}

I have a timer, that does this.Invalidate() on Tick, and the image is flickering. I've set this.DoubleBuffered = true in form constructor, and now my form does not even show anything, and if I resize it, it behaves like this:

1

What is that double-buffer thing that I am missing?

Upvotes: 0

Views: 449

Answers (1)

Hans Passant
Hans Passant

Reputation: 941505

using (Graphics g = e.Graphics)

The using keyword is the bug in this code. In essence it killed the double-buffer and the normal painting cycle cannot continue. Where "normal" is the content of the buffer getting blitted to the screen after your OnPaint() method completes. This screws up both the rendering of the background, which is why you see the back of the monitor, and the foreground, the image you drew.

Golden rule for using (or calling Dispose) is that you should only ever do that when you created the object. If you didn't, like you did not in this case, then you cannot assume that you "own" the object and you have to rely on the caller of your code to take care of it. Which it does, no need to help.

Fix:

e.Graphics.DrawImage(player.Sprite, new Rectangle(player.X, player.Y, 20, 20));
base.OnPaint(e);

Upvotes: 1

Related Questions