1. Home
  2. Computing & Technology
  3. Visual Basic

GDI+ Graphics in Visual Basic .NET
Using CreateGraphics to get a Graphics Object

By Dan Mabbutt, About.com

Sep 5 2008

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.

Explore Visual Basic
By Category
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Visual Basic
  4. Using VB.NET
  5. GDI+ Graphics in Visual Basic .NET

©2009 About.com, a part of The New York Times Company.

All rights reserved.