Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Building a Simple Object Example Project

The only way to really grasp what objects are and how they work is to use them. I've said this before, but I can't say it enough: Everything in Visual Basic .NET is an object. This has its good points and its bad points. One of the bad points is that in some instances, it now takes more code to accomplish a task than it did before—sometimes more characters, sometimes more statements. The functionality of Visual Basic .NET, on the other hand, is head and shoulders above Visual Basic 6. This has the effect of giving Visual Basic .NET a steeper learning curve than any previous version of Visual Basic.

Every project you've built so far uses objects, but you're now going to create a sample project that specifically illustrates using objects. If you're new to programming with objects, you'll probably find this a bit confusing. However, I'll walk you through step-by-step, explaining each section in detail.

The project you're going to create consists of single form with one button on it. When the button is clicked, a line will be drawn on the form beginning at the upper-left corner of the form and extending to the lower-right corner.


In Hour 18, "Working with Graphics," you'll learn all about the drawing functionality within Visual Basic.

Creating the Interface for the Drawing Project

Follow these steps to create the interface for your project:

  1. Start Visual Basic .NET.

  2. Create a new Windows Application project titled Object Example.

  3. Rename the default form fclsObjectExample (by using the Properties window), and change the form's Text property to Object Example.

  4. Make this form the Startup object by right-clicking Object Example in the Solution Explorer window, choosing Properties, and then selecting fclsObjectExample from the Startup object drop-down list. Click OK to close the dialog box.

  5. Add a new button to the form and set its properties as shown in the following table:




Writing the Object-Based Code

You're now going to add code to the Click event of the button. I'm going to explain each statement, and at the end of the steps, I'll show the complete code listing.

  1. Double-click the button to access its Click event.

  2. Enter the first line of code as follows (remember to press Enter at the end of each statement):

    Dim objGraphics As Graphics

    Here you've just created a variable that will hold an instance of an object. Objects don't materialize out of thin air; they have to be created. When a form is loaded into memory, it loads all its controls (that is, creates the control objects), but not all objects are created automatically like this. The process of creating an instance of an object is called instantiation. When you load a form, you instantiate the form object, which in turn instantiates its control objects. You could load a second instance of the form, which in turn would instantiate a new instance of the form and new instances of all controls. You would then have two forms in memory, and two of each used control.

    To instantiate an object in code, you create a variable that holds a reference to an instantiated object. You then manipulate the variable as an object. The Dim statement you wrote in step 2 creates a new variable called objGraphics, which holds a reference to an object of type Graphics. You learn more about variables in Hour 11.

  3. Enter the second line of code exactly as shown here:

    objgraphics = Me.CreateGraphics

    CreateGraphics is a method of the form (remember, the keyword Me is shorthand for referencing the current form). Under the hood, the CreateGraphics method is pretty complicated, and I discuss it in detail in Hour 18. For now, understand that the method CreateGraphics instantiates a new object that represents the client area of the current form. The client area is the gray area within the borders and title bar of a form. Anything drawn onto the objGraphics object will appear on the form. What you've done is set the variable objGraphics to point to an object that was returned by the CreateGraphics method. Notice how values returned by a property or method don't have to be traditional values such as numbers or text; they could also be objects.

  4. Enter the third line of code as shown next:


    This statement clears the background of the form using whatever color the user has selected as the Windows Control color, which Windows uses to paint forms.

    How does this happen? In step 3, you used the CreateGraphics method of the form to instantiate a new graphics object in the variable objGraphics. With the code statement you just entered, you're calling the clear method of the objGraphics object. The Clear method is a method of all Graphics objects used to clear the graphic surface. The Clear method accepts a single parameter: the color you want used to clear the surface.

    The value you're passing to the parameter looks fairly convoluted. Remember that "dots" are a way of separating objects from their properties and methods (properties, methods, and events are often called object members). Knowing this, you can discern that System is an object (technically it's a namespace, as discussed in Appendix A, "The 10,000-Foot View," but for our purposes it behaves just like an object) because it appears before any of the dots. However, there are multiple dots. What this means is that Drawing is an object property of the System object; that is, it's a property that returns an object. So, the dot following Drawing is used to access a member of the Drawing object, which in turn is a property of the System object. We're not done yet, however, because there's yet another dot. Again, this indicates that SystemColors, which follows a dot, is an object of the Drawing method, which in turn is...well, you get the idea. As you can see, object references can and do go pretty deep, and you'll use many dots throughout your code. The key points to remember are

    • Text that appears to the left of a dot is always an object (or namespace).

    • Text that appears to the right of a dot is a property reference or method call. If the text is followed by a set of parentheses, it's a method call. If not, it's a property.

    • Methods can return objects, just as properties can. The only surefire ways to know whether the text between two dots is a property or method is to look at the icon of the member in the IntelliSense drop-down or to consult the documentation of the object.

    The final text in this statement is the word Control. Because Control isn't followed by a dot, you know that it's not an object; therefore, it must be a property or method. Because you expect this string of object references to return a color value to be used to clear the graphic object, you know that Control in this instance must be a property or a method that returns a value (because you need the return value to set the Clear() method). A quick check of the documentation would tell you that Control is indeed a property. The value of Control always equates to the color designated on the user's computer for the face of forms and buttons. By default, this is a light gray (often fondly referred to as battleship gray), but users can change this value on their computers. By using this property to specify a color rather than supplying the actual value for gray, you're assured that no matter the color scheme used on a computer, the code will clear the form to the proper system color. System colors are explained in Hour 18.

  5. Enter the following statement. (Note: Do not press Enter until you're done entering all the code shown here. The code appears on two lines only because of the size restriction of this page.)

    objgraphics.DrawLine(system.Drawing.Pens.Blue, 0, 0,
               Me.DisplayRectangle.Width, Me.DisplayRectangle.Height)

    This statement draws a blue line on the form. Within this statement is a single method call and three property references. Can you tell what's what? Immediately following objGraphics (and a dot) is DrawLine. Because no equal sign is present, you can deduce that this is a method call. As with the Clear method, the parentheses after DrawLine are used to enclose a value passed to the method. The DrawLine accepts the following parameters in the order in which they appear here:

    • A pen

    • X value of first coordinate

    • Y value of first coordinate

    • X value of second coordinate

    • Y value of second coordinate

    The DrawLine method draws a straight line between coordinate one and coordinate two, using the pen specified in the Pen parameter. I'm not going to go into detail on pens here (refer to Hour 18), but suffice it to say that a pen has characteristics such as width and color. Looking at the dots once more, notice that you're passing the Blue property of the Pens object. Blue is an object property that returns a predefined Pen object that has a width of 1 pixel and the color blue.

    You're passing 0 as the next two parameters. The coordinates used for drawing are defined such that 0,0 is always the upper-left corner of a surface. As you move to the right of the surface, X increases, and as you move down the surface, Y increases; you can use negative values to indicate coordinates that appear to the left or above the surface. The coordinate 0,0 causes the line to be drawn from the upper-left corner of the form's client area.

    The object property DisplayRectangle is referenced twice in this statement. DisplayRectangle is an object of the form that holds information about the client area of the form. Here, you're simply getting the Width and Height properties of the client area and passing them to the DrawLine method. The result is that the end of the line will be at the lower-right hand corner of the form's client area.

  6. Lastly, you have to clean up after yourself by entering the following code statement:


    Objects often make use of other objects and resources. The underlying mechanics of an object can be truly boggling and are almost impossible to discuss in an entry-level programming book. The net effect, however, is that you must explicitly destroy most objects when you're done with them. If you don't destroy an object, it might persist in memory and it might hold references to other objects or resources that exist in memory. This means you can create a memory leak within your application that slowly (or rather quickly) munches system memory and resources. This is one of the cardinal no-no's of Windows programming, yet the nature of using resources and the fact you're responsible for telling your objects to clean up after themselves makes this easy to do. If your application causes memory leaks, your users won't call for a plumber, but they might reach for a monkey wrench....

    Objects that must explicitly be told to clean up after themselves usually provide a Dispose method. When you're done with such an object, call Dispose on the object to make sure it frees any resources it might be holding.

    For your convenience, here are all the lines of code:

    Dim objGraphics As Graphics
    objgraphics = Me.CreateGraphics
    objgraphics.DrawLine(system.Drawing.Pens.Blue, 0, 0, _
               Me.DisplayRectangle.Width, Me.DisplayRectangle.Height)

    The statement calling DrawLine is shown here as two lines of code. At the end of the first line is an underscore (_). This character is a special character called a line continuation character, and it tells the Visual Basic compiler that the statement immediately following the character is a continuation of the current statement. You can, and should, use this character to break up long statements in your code.

Testing Your Object Example Project

Now the easy part. Run the project by pressing F5 or by clicking the Start button on the toolbar. Your form looks pretty much like it did at design time. Clicking the button causes a line to be drawn from the upper-left corner of the form's client area to the lower-right corner (see Figure 3.7).


If you receive any errors when you attempt to run the project, go back and make sure that the code you entered exactly matches the code I've provided.

Figure 3.7Figure 3.7 Simple lines and complex drawings are accomplished using objects.

Resize the form, larger or smaller, and click the button again. Notice that the form is cleared and a new line is drawn. If you were to omit the statement that invokes the Clear method (and you're welcome to stop your project and do so), the new line would be drawn, but any and all lines already drawn would remain.


If you use Alt+Tab to switch to another application after drawing one or more lines, the lines will be gone when you come back to your form. In fact, this will occur anytime you overlay the graphics with another form. In Hour 18, you'll learn why this is so and how to work around this behavior.

Stop the project now by clicking Stop Debugging on the Visual Basic .NET toolbar and then click Save All to save your project. What I hope you've gained from building this example is not necessarily that you can now draw a line (which is cool), but rather an understanding of how objects are used in programming. As with learning almost anything, repetition aids in understanding. That said, you'll be working with objects a lot throughout this book.

  • + Share This
  • 🔖 Save To Your Account