We have already seen this in previous articles. We can override the onPaint method by defining it as follows:
Protected Overrides Sub OnPaint(ByVal
args As PaintEventArgs)
'Add your drawing code here
End Sub
Then we can use the Graphics property of PaintEventArgs to draw, lines, shapes,
text, and images. Listing 13.4 draws a few graphics shapes and text on our
form's OnPaint method. To test this code, create a Windows application and add
the code to it.
LISTING 13.4: Using OnPaint to draw
Protected Overrides Sub OnPaint(ByVal
args As PaintEventArgs)
'Get the Graphics object from PaintEventArgs
Dim g As
Graphics = args.Graphics
'Draw rectangle
g.DrawRectangle(New Pen(Color.Blue, 3), New
Rectangle(10, 10, 50, 50))
'Fill ellipse
g.FillEllipse(Brushes.Red, New
Rectangle(60, 60, 100, 100))
'Draw text
g.DrawString("Text",
New Font("Verdana",
14), New SolidBrush(Color.Green), 200, 200)
End Sub
Using Visual Studio .NET to add the Paint Event Handler
If you are using Visual Studio .NET, the easiest way to add a paint event
handler is to use the Properties windows of a form or control ad add a paint
event handler.
Disposing of Graphics Objects
It is usually good programming practice to dispose of objects when you're
finished using them. But it may not always be the best practice. A Graphics
object must always be disposed of it was created via the CreateGraphics method
or other "CreateFrom" methods. If we use a Graphics object on a paint event or
the OnPaint method from the PaintEventArgs.Graphics property, we do not have to
dispose of it.
NOTE
Do not dispose of Graphics objects associated with Windows controls such as
Button, ListBox, or DataGrid.
If you create objects such as pens and brushes, always dispose of them. Although
it is acceptable practice to rely on the garbage collector, doing so may often
be at the expense of application performance. Garbage collection can be a costly
affair because the garbage collector checks the memory for objects that haven't
been disposed of, and this process absorbs processor time. However, the Dispose
method of an object tells the garbage collector that the object is finished and
ready to be disposed of. Calling the Dispose method eliminates the need to have
the garbage collector check memory and thus saves processor time.
In Web pages, it is always food practice to dispose of objects as soon as they
are done being used.
The OnPaintBackground Method
The OnPaintBackground method paints the background of a control. This method is
usually overridden in the derived classes to handle the event without attaching
a delegate. Calling the OnPaintBackground method calls OnPaintBackground of the
base automatically, so we do not need to call it explicitly.