As a programmer, you will be writing lots of code. After reading Chapter 2, "Creating Your First Windows Application," you should be familiar with some basic terms used to describe parts of the code: variables, events, properties, and so on. In this section, we will attempt to familiarize you with several terms frequently used to describe and categorize Visual Basic code structures. Understanding Objects and Classes To understand Visual Studio .NET, you must understand the concept of an object. In the real world, an object is a thing such as the car you drove to work this morning, or the DVD movie you watched last night. Objects with similar characteristics (such as all cars or all DVDs) can be grouped together into a class. For example, the following statement describes the DVD class: DVDs contain a movie title and are 5 inches in diameter. They can be played in a video disc player or a computer. Suppose you go to the video store and rent several DVD movies. All the movies are a member of the same class, but each movie is a separate object. In a lot of books, the terms class and object are used interchangeably. This is fine for discussion purposes, but as a developer you should be aware that there is a difference. Note A class is a template that describes objects belonging to the class. An object is an instance of a class. For example, "Brian's truck" is an instance of the truck class. So how do we apply the concept of objects to Visual Basic programming? Just as there are objects in real life, there are objects in program code. You can use objects and classes (both of your own design and those provided by others) in your programs to help solve a problem. This is known as object-oriented programming (OOP). The strict definition of OOP and creating your own objects is discussed in Chapter 9, "Creating Code Components." For more on creating your own classes, p.223 Understanding Members An object has has attributes that make it unique, such as the name of the movie contained on a DVD. Objects can also perform tasks. In the case of a car, accelerate or honk horn are things you can do with a car object. In Chapter 2, we described the controls we placed on a form as objects. A Button control has properties (such as length, width, text) as well as events, which allow the object to trigger an action. We also called some methods contained within objects, such as the ToString method used to convert an object's value to a character string. In Visual Basic, the definition of a class may include properties, methods, and events. Collectively these parts of an object are known as its members. Consider the following sample class definition for a car shown in Figure 5.1 (some of the code listings have been collapsed). Figure 5.1. As you add methods to a class, they will appear in the Method drop-down box in the upper-right corner of the code editor. As you can see from Figure 5.1, the Car class contains properties, methods, and events declared with VB code. The modifiers (such as Public and Private) that precede the member definition are used to control the access to the member. For example, Private members cannot be accessed from VB code outside the class definition, but Public members can. In our sample, users of the Car class cannot access the private Speed variable directly; they must use the CurrentSpeed property. All the different types of access and their meanings will be discussed in Chapter 8, "Program Tasks with Functions and Procedures." For more on access to members, p.201 Understanding Method Types Of all the different types of members, the term method bears some clarification. Methods are units of code within a class that perform a task, but they come in several different forms. The following are all statements you might read or hear that indicate execution of a method: Each of these statements is a variation on the same thing but has a specific connotation. Let's look at the two most common types of methods, functions and subroutines. The following function gets the current system time: Private Function GetCurrentTime(Optional ByVal IncludeSeconds As Boolean = True) As String If IncludeSeconds = False Then Return Format(Now, "hh:mm") Else Return Format(Now, "hh:mm:ss") End If End Function The previous sample code is known as a function because it has a value, much like a mathematical function. The As String declaration at the end of the function declaration indicates the type of value returned by the function. Like a mathematical function, a function in VB also may have input parameters that control the return value. The IncludeSeconds parameter determines whether the function returns the seconds. Another type of method is the subroutine, or procedure. The GetCurrentTime function rewritten as a procedure would look like this: Private Sub GetCurrentTime(ByRef CurrentTime As String, Optional ByVal IncludeSeconds As Boolean = True) If IncludeSeconds = False Then CurrentTime = Format(Now, "hh:mm") Else CurrentTime = Format(Now, "hh:mm:ss") End If End Sub Unlike the function, the subroutine itself does not have a value. However, it can still send values back to the caller using output parameters. In the previous example the ByRef parameter CurrentTime contains the desired result. For more on parameters, p.201 The previous examples demonstrate two ways of accomplishing the same task, but with slightly different syntax. The following lines of code show how to call the function and subroutine. In each case, the output value of the GetCurrentTime method is assigned to a string variable, ReturnValue. ReturnValue = GetCurrentTime(False) 'Calls the function GetCurrentTime(ReturnValue,False) 'Calls the sub As you can see from the example, the return value of a function can be assigned to a variable using the equals (=) assignment operator. The parameters to a method call are enclosed in parentheses. Note The procedure call syntax has changed slightly in this version of Visual Basic. In Visual Basic 6.0, you had to use the Call keyword when calling a procedure with parentheses around the parameters, or omit the parentheses. In Visual Basic .NET the Call keyword is optional and parentheses are always used. Understanding Events The concept of events and event-driven programming is essential to developing applications for the Windows environment. With a text-based user interface (such as DOS) that is running a single program at a time, control over program execution is straightforward. However, Windows applications are inherently event-driven, meaning that the flow of program execution is controlled by the events that occur as the program is running. The user or system can initiate events in any order. For example the user may click a button, scroll a list box, or close a window. This seemingly un-ordered execution of code is often a stumbling block for programmers used to mainframe environments attempting to learn Visual Basic. Note As one astute reader pointed out, event-driven programs have actually been around for a long time. For example, the program that drives air-traffic control radar reacts to an external event (the presence of a plane) and updates the screen. Selecting an Event Handler A special type of method, the event handler, allows you to write code to respond to events. In Chapter 2 and Chapter 3, "Creating Your First Web Application," you added code to the procedure that handled a Button control's Click event. An event is something external to your program. When an event fires it executes the procedure that handles the event. When the user clicks a button he is causing an event within the program, so there is an associated method that handles that event. Recall from Chapter 2 that you use the drop-down boxes at the top of the Code Editor window to select an event procedure. The object is selected in the Code window's upper-left drop-down list box (the Class box); the appropriate event procedure is selected in the upper-right drop-down list box (the Method box). When that object/event combination occurs at runtime, if code has been written for that combination, Visual Basic executes the code. If no code has been written for the combination, Visual Basic ignores the event. Figure 5.2 shows an example of an event procedure written for a specific control and event. Figure 5.2. Visual Basic responds to an event only if you write code for the event. Users of previous versions of Visual Basic will note that events are treated more like methods in Visual Basic .NET. While events in Visual Basic 6.0 had specialized parameters, event procedures in Visual Basic .NET have more generic arguments and are treated similarly to other types of methods. As you can see in Figure 5.2, a lightning bolt icon is displayed next to the names of the events during the process of selecting an event procedure. However, after selecting an event, the icon changes to a method icon, because the event procedure is really just a method within a class that handles the event. Tip If you enter a Code window by double-clicking an object, the Code window automatically selects that object's most commonly used event procedure. For example, if you double-click a command button at design time, the Code window is opened to that command button's Click event procedure. Writing an Event Procedure To understand how events occur continuously throughout your program, follow these steps to write a simple example: -
Start a new Windows Application project. -
Double-click the form in the designer window to open the Code window. By default, if no other code exists for the form, you are placed in the form's Click event procedure. -
From the Class selection box, select the Base Class Events. (Note this will be the last item in the list of objects.) -
From the Method box, select the MouseMove event. Note Notice that when you make a selection, Visual Basic automatically sets up the skeleton of a procedure with the procedure's name and the End Sub statement (which denotes the end of the procedure). The procedure name for an event procedure contains the name of the object and the name of the event. In this example, Form1 is the object and MouseMove is the event. Notice that the MouseMove event procedure also has some parameters; The sender parameter contains information about the caller, and the e parameter contains arguments specific to this event, in this case the coordinates of the mouse. -
At this point, you can write program statements to take whatever action(s) should happen in response to an occurrence of the event. Add the following line of code to the event procedure: Me.Text = "The mouse coordinates are " & e.X & "," & e.y Your event procedure should now look like this: Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove Me.Text = "The mouse coordinates are " & e.X & "," & e.Y End Sub The preceding code displays the values of the X and Y parameters in the form's title bar by setting the Text property of the form. Click Visual Basic's Start button, or press F5, and move the mouse pointer over the form. You should see the form's title change as the mouse pointer moves. Most of these events you encounter in Visual Basic are the direct result of actions initiated by the users; however, other objects, including those of your own creation, invoke some events. To learn more about creating and raising your own events, please see Chapter 9. |