1. Computing & Technology

Discuss in my forum

GDI+ Graphics in Visual Basic .NET

Using CreateGraphics to get a Graphics Object

By , About.com Guide

The second method to get a Graphics object for your code uses a CreateGraphics method that is available with many components. The code looks like this:

Private Sub Button1_Click( _
   ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles Button1.Click
   Dim g = Me.CreateGraphics
   g.DrawString("About Visual Basic" & vbCrLf _
   & "and GDI+" & vbCrLf & "A Great Team", _
   New Font("Times New Roman", 20), _
   Brushes.Firebrick, 0, 0)
End Sub

There are a couple of differences here. This is in the Button1.Click event because when Form1 repaints itself in the Load event, our graphics are lost. So we have to add them in a later event. If you code this, you'll notice that the graphics are lost when Form1 has to be redrawn. (Mimimize and maximize again to see this.) That's a big advantage to using the first method.

Most references recommend using the first method since your graphics will be repainted automatically. GDI+ can be tricky!

Part 2 of our series discusses GDI+ vector graphics and uses the Paint event of a Panel control to draw trigonometric functions.

©2012 About.com. All rights reserved.

A part of The New York Times Company.