Of course! The
Form
does not hold graphics; and this is done so for a good reason. The form is rendered every time part of it is invalidated, which happens when a part of form is shown when it was masked by some other window and later shown.
You need to handle the event
Form.Paint
or override its method
Form.OnPaint
. For example, place this code in your form's constructor:
this.Paint += (sender, eventArgs) => {
Graphics graphics = eventArgs.Graphics;
};
As a rule of thumb, you should not create an instance of
System.Drawing.Graphics
, use the one passed to you in event arguments parameter.
Now, to change the rendered graphics (animation, any kind of interactive behavior such as in gaming or drawing application) make the rendering method (shown as anonymous method above) depending on some data structure; and make this data structure a field(s) of your form. When you change data, the rendering will change; but how to trigger re-drawing? You need to trigger sending the message
WM_PAINT
to the form.
This is done by calling
Form.Invalidate
(inherited from
Control.Invalidate
. You can improve performance using
Invalidate
with parameters (
Rectangle
or
Region
) to invalidate just some part of the scene.
—SA