378 Part III Designing the User Interface
Using the Form’s Paint Event
If you test the previous DrawLine method in a program, you’ll notice that the line you created
lasts, or persists, on the form only so long as nothing else covers it up. If a dialog box opens
on the form momentarily and covers the line, the line is no longer visible when the entire
form is visible again. The line also disappears if you minimize the form window and then
maximize it again. To address this shortcoming, you need to place your graphics code in
the form’s Paint event procedure so that each time the form is refreshed, the graphics are
repainted, too.
In the following exercise, you’ll create three shapes on a form by using the form’s Paint
event procedure. The shapes you draw will continue to persist even if the form is covered or
minimized.
Create line, rectangle, and ellipse shapes
- Start Visual Studio, and create a new Windows Forms Application project named
My Draw Shapes. - Resize the form so that it’s longer and wider than the default form size.
You’ll need a little extra space to create the graphics shapes. You won’t be using any
Toolbox controls, however. You’ll create the shapes by placing program code in the
form’s Form1_Paint event procedure.
- Set the Text property of Form1 to “Draw Shapes .”
- Click the View Code button in Solution Explorer to display the Code Editor.
- At the top of the Code Editor, just below the Form1 .vb tab, click the Class Name arrow,
and then click Form1 Events.
Form1 Events is the list of events in your project associated with the Form1 object. - Click the Method Name arrow, and then click the Paint event.
- The Form1_Paint event procedure appears in the Code Editor.
This event procedure is where you place code that should be executed when Visual
Basic refreshes the form.
- Within the Form1_Paint event procedure, type the following program code:
'Prepare GraphicsFun variable for graphics calls
Dim GraphicsFun As Graphics
GraphicsFun = Me.CreateGraphics
'Use a red pen color to draw a line and an ellipse
Dim PenColor As New Pen(Color.Red)
GraphicsFun.DrawLine(PenColor, 20, 30, 100, 80)
GraphicsFun.DrawEllipse(PenColor, 10, 120, 200, 160)