This is because you are doing it wrong. Actually, this is a pretty common mistake.
The rendering of graphics persists only if you perform it on each
WM_PAINT
Windows message. For this purpose, you should handle the event
System.Windows.Forms.Control.Paint
, or, better yet, override the virtual method
System.Windows.Forms.Control.OnPaint
in your derived control of form class. The message
WM_PAINT
will be triggered each time some area of the control needs re-painting, for example, when a part of a control was hidden under some other window. Normally, you do all the changes in graphics in some data, and when you change the data (with your mouse events or by any other action), you need to force sending the message. This is done via one of the
System.Windows.Forms.Control.Invalidate
methods. Sometimes, it's good to use the method
Invalidate
with parameters (
Region
or
Rectangle
), to invalidate just the part of the scene, which can help you to improve performance.
Also, you should not create an instance of
System.Drawing.Graphics
(please see my comment to the question). You should use the instance passed to your handler of the event
System.Windows.Forms.Control.Paint
or the virtual method
System.Windows.Forms.Control.OnPaint
as the event parameter.
Please see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.drawing.graphics.aspx[
^].
Please see my past answers to related questions:
Drawing Lines between mdi child forms[
^],
capture the drawing on a panel[
^],
What kind of playful method is Paint? (DataGridViewImageCell.Paint(...))[
^].
—SA