1

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?

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • 1
    Why are you calling `panelMap.Invalidate();` in a paint event handler? – Hossain Muctadir Mar 05 '14 at 05:26
  • Oh, my fault, thank you. Nevertheless, it doesn't help with the problem. – Yeldar Kurmangaliyev Mar 05 '14 at 05:32
  • Try getting rid of the `using` statement. You didn't create the instance of the `Graphics` object and disposing of it may be clearing the work you did before it is actually painted onto the screen. – TyCobb Mar 05 '14 at 05:33
  • A rule of thumb for IDisposeable objects: if you got it returned from a function dispose it (put it in a `using` block), if you got it returned from a property don't dispose it (as it is the parent object's responsibility to dispose it) – Scott Chamberlain Mar 05 '14 at 06:09

2 Answers2

5

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);
}
TyCobb
  • 8,909
  • 1
  • 33
  • 53
0

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.
ssett
  • 432
  • 3
  • 6
  • Never "comment out" any code besides for testing purposes. Comments in source code are for human readers of the code telling them why the code is written like it is. If a portion of the code is not necessary or even faulty, just remove it! – abto Mar 05 '14 at 06:17