Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

C# Double Buffered not painting

I simulate map navigation and draw generated part of the map on a panel. Since image is flickering I have to use double buffering.

Here's my Panel code:

public class MapPanel : System.Windows.Forms.Panel
    {
        public MapPanel()
        {
            DoubleBuffered = true;
            ResizeRedraw = true;
        }
    }

And I have the following method:

public void panelMap_Paint(object sender, PaintEventArgs e)
        {
            using (Graphics g = e.Graphics)
            {
                g.DrawImage(mapController.GetCurrentMap(), 0, 0, panelMap.Width, panelMap.Height);
            }
        }

I'm not calling this method. I have the following code in .Designer.cs:

this.panelMap.Paint += new PaintEventHandler(this.panelMap_Paint);

And call Invalidate() in MouseMove. I'm sure that this event occurs, I've checked it. Everything seems to be correct.

And then the image is not drawing. I mean, the panel is empty and seems to be transparent or colored in default control color. However, if I turn double buffering off, the image is properly drawn, but, obviously, it's flickering. Could you help me?

Upvotes: 1

Views: 1202

Answers (2)

TyCobb
TyCobb

Reputation: 9089

Remove the using statement. You are disposing of the Graphics object before it is used to draw to the screen.

As mentioned, you should also remove the Invalidate() call from the paint method.

public void panelMap_Paint(object sender, PaintEventArgs e)
{
    var g = e.Graphics;
    g.DrawImage(mapController.GetCurrentMap(), 0, 0, panelMap.Width, panelMap.Height);
}

Upvotes: 5

ssett
ssett

Reputation: 432

You should comment out the following code

//panelMap.Invalidate();

According to MSDN

Invalidates the entire surface of the control and causes the control to be 
redrawn.

Upvotes: 0

Related Questions