Home > Articles > Programming > Windows Programming

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

Building an 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 that Visual Basic .NET has a steeper learning curve than any previous version of Visual Basic.

You're about to create a sample project that uses 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.

NOTE

In Hour 10, "Drawing and Printing," 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 fclsDrawing (by using the Properties window), and change the form's Text property to Object Example.

  4. Right-click the project name Object Example in the Solution Explorer and choose Properties from its context menu.

  5. Open the Startup object dropdown list and choose fclsDrawing. Click OK to save your changes and close the Property Pages dialog box.

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

  7. Property

    Value

    Name

    btnDraw

    Text

    Draw

    Location

    112,120

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.

Object Example Project

  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):

  3. Dim objGraphics As Graphics

    Here you've just created 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 12, "Using Constants, Data Types, Variables, and Arrays."

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

  5. objgraphics = Me.CreateGraphics

    CreateGraphics is a method of the form (remember, the keyword Me is shorthand for referencing the current form). The CreateGraphics method is pretty complicated under the hood, and I discuss it in detail in Hour 10. 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 appears 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 can also be objects.

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

  7. objgraphics.Clear(system.Drawing.SystemColors.Control)

    This statement clears the background of the form using whatever color the user has selected as the Windows forms color.

    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 to which you want the surface cleared.

    The value you're passing to the parameter looks fairly convoluted. Remember that "dots" are a method of separating objects from their properties and methods. Knowing this, you can discern that System is 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; 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 is 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.

    • Text that appears to the right of a dot is a property reference or method call.

    • Methods are never objects. Therefore, text that appears between two dots is a property that returns an object. Such a property is called an object property.

    The final text in this statement is the word Control. Because Control is not 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 must be a property or a method that returns a value. 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. 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 are 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 10.

  8. Enter the following statement (Note: Press Enter after entering the underscore character on the first line so that each line of the statement shown here appears on its own line in the code editor):

  9. objgraphics.DrawLine(system.Drawing.Pens.Chartreuse, 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.

    This statement draws a chartreuse 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 10), 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 Chartreuse property of the Pens object. Chartreuse is an object property that returns a predefined Pen object that has a width of 1 pixel and the color chartreuse.

    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.

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

  11. objgraphics.Dispose()

    Objects often make use of other objects and resources. The underlying mechanics of an object can be truly boggling and 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.

    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.Clear(system.Drawing.SystemColors.Control)
    objgraphics.DrawLine(system.Drawing.Pens.Chartreuse, 0, 0, _
               Me.DisplayRectangle.Width, Me.DisplayRectangle.Height)
    objgraphics.Dispose()

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).

NOTE

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

Figure 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.

NOTE

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 Hour 10, 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 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