Oh gosh, you do it all wrong! Forms do not persist rendered graphics at all. Here is what to do:
You need to do all your drawing in the overridden method
OnPaint
or event handler
Paint
. In both cases, for drawing, use the instance of the
System.Drawing.Graphics
passed in the event argument parameter. Your rendering method will be called each time
WM_PAINT
Windows message is dispatched to your window, for example, when you hide and show you form again or when your graphics is masked by some other window and later shown again. Never create an instance of Graphics for your control, always use the one from the event argument parameter. In fact, sometimes you can do it, but it's much more advanced technique. In your case, just don't do it.
What do to do change graphics? You're using some data for rendering. Change this data, that's it. Next time
WM_PAINT
comes, your new data will be used for re-drawing. But if nothing else is triggered, how to programmatically trigger this
WM_PAINT
? The only one valid way to do it is calling
System.Windows.Forms.Control.Invalidate
on the control where you render the graphics. For performance sake, you may want to use
Invalidate
with a parameter (Rectangle or Region) to invalidate only the part of the scene which really needs update.
To avoid flicker, you also may need double buffering options, see
Control.SetStyle
. It's protected, so do it in the derived
Control
class. If this is a
Form
, you derive it from
System.Windows.Forms.Form
anyway.
For a code sample, see this:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.onpaint.aspx[
^].
Just in case, if I missed something, check my past answers (essentially the same):
What kind of playful method is Paint? (DataGridViewImageCell.Paint(...))[
^],
Drawing Lines between mdi child forms[
^].
[EDIT]
Just in case, some more references to my past answers:
How do I clear a panel from old drawing[
^],
draw a rectangle in C#[
^],
Append a picture within picturebox[
^];
Drawing Lines between mdi child forms[
^],
capture the drawing on a panel[
^],
What kind of playful method is Paint? (DataGridViewImageCell.Paint(...))[
^],
How to speed up my vb.net application?[
^].
—SA