Drawing with Windows Forms
Download supporting files at www.apress.com.
The files for this tip are in the “Ch7—Drawing” folder.
This book deals primarily with the business world. We’ve talked about databases,
setting up Web services, and utilizing powerful encryption algorithms. But we
haven’t discussed drawing in your application. So, in the interest of developing
your all-round super programmer mindset, let this tip serve as a quick overview.
First off, you may have noticed that there’s no Shape control with .NET. If you
want to draw, you need to revert to code. Thankfully, it’s not all sticky API code
anymore. Microsoft has repackaged all that old drawing functionality, added a
little more, and christened it GDI+ (the old system was known as the GDI,
standing for graphical device interface).
How can you use it? Basic drawing is actually pretty simple. You need to know
just three core pieces of information. First, when drawing, you need a digital
“sheet of paper” to work with. This is an object based on the Graphicsclass, and, if
you worked a lot with graphics in VB6, you’re probably best imagining this as an
encapsulated Windows device context.
When you have this area to work on, you need to know what tools to work
with, and there are really only two possibilities here. There’s our second item, the
Penclass, which allows you to set up the style of line you want. And then there’s our
third item, the Brushclass, which is designed for filling in areas and defining how
that “fill” will look.
Once you have the items, you use methods of the Graphicsobject (our sheet of
paper) to put the tools into work. All the Draw...methods take your pen style and
draw something, and all the Fill...methods take your brush style and fill some-
thing. So, for example, I may call the FillRectanglefunction of my Graphicsobject,
passing in a purple Brushobject and various dimensions, and a purple rectangle
would be drawn for me.
Let’s look at a little sample code to help explain away this weird-sounding
phenomenon. This commented snippet is intended to run behind a Windows
' Get Graphics object from our form, our "sheet of digital drawing paper"
Dim objGraphics As System.Drawing.Graphics = Me.CreateGraphics
' Create new Pen, color blue, width 10
Dim objPen As New Pen(Color.Blue, 10)
' Draw line using pen from