This is
not a whole application. How do you know that
Form1_Paint
is a handler added to an invocation list of the event
Paint
. Relying on the Designer? There are many cases when the Designer only makes development slower.
As you already have your
Form
class, why handling the event at all? Just overriding
OnPaint
does exact same thing. Now, where is the mistake? This is creation of the instance of
System.Drawing.Graphics
using its constructor. You should use the instance which is already passed to you in the handler method of
Paint
or
OnPaint
; it is passed in event arguments parameter.
More mistakes:
Font
and
Brush
are not disposed, so you will have a permanent unmanaged resource leak. This is important enough, so it should also handle possible exceptions. Normally, it is done using try-finally, but the equivalent behavior is achieved using
using
statement (not to by confused with
using
clause, see
http://msdn.microsoft.com/en-us/library/yh598w02.aspx[
^]).
Also, there is not need to create a solid brush of an well-known color.
After all fixes:
protected override void OnPaint(PaintEventArgs eventArgs) {
using (Font myFont = new System.Drawing.Font("Helvetica", 40, FontStyle.Italic)) {
e.Graphics.DrawString("Hello C#", myFont, System.Drawing.Brushes.Red, 30, 100);
}
}
If you need graphics to move, and change data used by
OnPaint
, you need to call
Control.Invalidate
. You can try to improve performance using
Control.Invalidate
with parameters (
Region
or
Rectange
) to refresh only the part of the scene.
See also my past answers:
What kind of playful method is Paint? (DataGridViewImageCell.Paint(...))[
^],
Drawing Lines between mdi child forms[
^],
capture the drawing on a panel[
^],
How do I clear a panel from old drawing[
^] (this one helps to prevent the very common abuse of
PictureBox
).
—SA