The graph of panel will go after the form is minim

2019-09-21 09:58发布

问题:

I have a panel in my form named Pan_Paint and I have the code below:

Graphics graph = Pan_Paint.CreateGraphics();
graph.FillEllipse(new SolidBrush(Blue), 10, 10, 100, 100);

When I minize the form, and the when I restore it, the line will disappear. Or when I press Tab Button, the same thing will happen. What can I do to fix that? Thank you.

回答1:

This is basic.

You either need to cache all drawing in some data structures and have them drawn in the Paint event. Again and again, whenever windows needs to restore the Screen.

You initially call the Paint event by doing an Panel.Invalidate() whenever you have added some drawing actions to your drawing queues.

No way around that other than:

Draw them into the Image of a PictureBox (not just onto the PictureBox!)..

Here is the code to do it right with a PictureBox and also how to do it wrong:

  // this will change the Image of a PictureBox, assuming it has one.
  // These changes are persistent:

    using (Graphics G = Graphics.FromImage(pictureBox1.Image))
    {
        G.DrawEllipse(Pens.Red, new Rectangle(0, 0, 444, 444));
        pictureBox1.Invalidate();
    }

  // This is the wrong, non-persistent way to paint, no matter which control: 
  //The changes go away whenever the Window is invalidated:

    using (Graphics G = pictureBox2.CreateGraphics() )
    {
        G.DrawEllipse(Pens.Green, new Rectangle(0, 0, 444, 444));
    }

Instead create a class of drawing actions and loop over a list of them in the Paint event!