Using Visual Basic 6

Previous chapterNext chapterContents


- 6 -
Working with Properties, Methods, and Events


What Are Properties, Methods, and Events?


Using containers

Remember that a container is an object--such as a form or the Frame or PictureBox controls--that can contain other controls.


Put simply, properties describe objects. Methods cause an object to do something. Events are what happens when an object does something.

Every object, such as a form or control, has a set of properties that describe it. Although this set isn't identical for all objects, some properties--such as those listed in Table 6.1--are common to most controls. You can see every property for a given control by looking at the Properties window in the IDE.

TABLE 6.1  Common Properties of Visual Basic Controls

Property Description
Left The position of the left side of a control with respect to its container
Top The position of the top of a control with respect to its container
Height A control's height
Width A control's width
Name The string value used to refer to a control
Enabled The Boolean (True/False) value that determines whether users can manipulate the control
Visible The Boolean (True/False) value that determines whether users can see the control

Another important property to consider is BorderStyle, which determines the window elements (title bar, Maximize and Minimize buttons, and so forth) a form will have. Table 6.2 summarizes the six BorderStyle settings; Figure 6.1 shows the same form, displayed with each setting.

TABLE 6.2  The Six Settings of the BorderStyle Property

Setting Description
0-None No borders, no title bar, not movable. Use this as a backdrop for a splash screen.
Setting Description
1-Fixed Single Not sizable by dragging borders but can have Maximize and Minimize buttons. Use this for any fixed-size window for which you want a button to appear in the taskbar.
2-Sizable (default) Sizable by dragging borders and by using Maximize and Minimize buttons. Use this for typical programs.
3-Fixed Dialog Not sizable and no Maximize/Minimize buttons. Use this for simple forms such as a password dialog.
4-Fixed ToolWindow Similar to 3-Fixed Dialog except that the title bar is shorter and the title bar font and Close button are correspondingly smaller. Use this for floating toolbars.
5-Sizable ToolWindow Similar to a 4-Fixed ToolWindow except that it's sizable by dragging the border. Use this for windows such as the Visual Basic Properties window.

FIGURE 6.1 The BorderStyle property of a form can be set to one of six different styles. Notice that some styles can look exactly the same as other styles.

Methods are blocks of code designed into a control that tell the control how to do things, such as move to another location on a form. Just as with properties, not all controls have the same methods, although some common methods do exist, as shown in Table 6.3.

TABLE 6.3  Common Methods of Visual Basic Controls

Method Use
Move Changes an object's position in response to a code request
Drag Handles the execution of a drag-and-drop operation by the user
SetFocus Gives focus to the object specified in the method call
ZOrder Determines the order in which multiple objects appear onscreen

Events are what happen in and around your program. For example, when a user clicks a button, many events occur: The mouse button is pressed, the CommandButton in your program is clicked, and then the mouse button is released. These three things correspond to the MouseDown event, the Click event, and the MouseUp event. During this process, the GotFocus event for the CommandButton and the LostFocus event for whichever object previously held the focus also occur.

Again, not all controls have the same events, but some events are shared by many controls (see Table 6.4). These events occur as a result of some specific user action, such as moving the mouse, pressing a key on the keyboard, or clicking a text box. These types of events are user-initiated events and are what you will write code for most often.


Using GotFocus and LostFocus

The GotFocus and LostFocus events relate to most other events because they occur whenever a new control becomes active to receive user input. This makes GotFocus and LostFocus useful for data validation, the process of making sure that data is in the proper format for your program. Be careful, though! Improperly coding these two events can cause your program to begin an endless loop, which will cause your program to stop responding.


TABLE 6.4  Common Events of Visual Basic Controls

Event Occurrence
Change The user modifies text in a combo box or text box.
Click The user clicks the primary mouse button on an object.
DblClick The user double-clicks the primary mouse button on an object.
DragDrop The user drags an object to another location.
DragOver The user drags an object over another control.
GotFocus An object receives focus.
KeyDown The user presses a keyboard key while an object has focus.
KeyPress The user presses and releases a keyboard key while an object has focus.
KeyUp The user releases a keyboard key while an object has focus.
Event Occurrence
LostFocus An object loses focus.
MouseDown The user presses any mouse button while the mouse pointer is over an object.
MouseMove The user moves the mouse pointer over an object.
MouseUp The user releases any mouse button while the mouse pointer is over an object.

The Relationship Between Properties, Methods, and Events


Right and bottom properties

It's important to remember that right and bottom properties don't exist in Visual Basic. Later, you'll see how to position an object by using the Top, Height, Left, and Width properties.


Although properties, methods, and events do different things, it's important to realize that they're often interrelated. For example, if you move a control with the Move method (most likely in response to an event), one or more of the control's position properties (Top, Height, Left, and Width) will change as a result. Because the control's size has changed, the Resize event occurs.

This interdependence means that you can sometimes accomplish the same task multiple ways in your code by manipulating object properties or methods. Consider the following code, which shows two ways to move a CommandButton:

`************************************************
`Move the commandbutton by setting the properties
`************************************************
cmdMove.Left = 100
cmdMove.Top = 100
`********************************************
`Move the commandbutton by using the Move method
`********************************************
txtMove.Move 100, 100

As another example, you can make a form appear and disappear from the screen by using its Visible property or its Show and Hide methods, as follows:

`***********************************************
` Make the form visible by setting the property
`***********************************************
frmMyForm.Visible=True
`***************************************
` Hide the form by setting the property
`***************************************
frmMyForm.Visible=False
`*********************************************
` Make the form visible by using the Show method
`*********************************************
frmMyForm.Show
`*************************************
` Hide the form by using the Hide method
`*************************************
frmMyForm.Hide

The Importance of Event-Driven Programming

When you create a program in Visual Basic, you'll generally be doing event-driven programming. Event-driven programming means that most of the code you write will be run as users do things within your program or even when certain things happen in Windows--when events occur. Of course, programming this way means that you have to know when events occur and have to write code that will make your program do something in response to the event.

Fortunately, Windows and Visual Basic do most of the work for you. Whenever an event takes place, Windows sends out a message to your program. Your program reads this message, and then runs the code you've attached to the event. If you don't specify code for an event, your program will simply ignore the event.

Generally, this code is known as a procedure, defined as any block of code that can be called from within your application. This code might be used to move objects around on a form, calculate a value from a formula, or write data to a database. No matter the purpose, a procedure always uses this format:

[Public|Private] [Static] Sub|Function|Property _
   function_name (arguments) [As Type]
{...Your procedure code...}
End Sub|Function|Property

An event procedure is the place in your project where you put the code that will run when an event occurs. To write an event procedure, you must access the Code window for your object by doing one of the following:

FIGURE 6.2 The code you write in an event procedure will run whenever the event occurs.

Visual Basic automatically generates an event procedure when you select an event in the Code Window. In Figure 6.2, notice that you name event procedures by joining the object's name and the event name with an underscore character (cmdExit_Click()). When the event procedure in this example is run, it will display a dialog when the user clicks the CommandButton named cmdExit.

Using Properties, Methods, and Events in a Sample Program

Now is a good time to bring together everything you've learned about properties, methods, and events in an application named MoveIt (see Figure 6.3).

FIGURE 6.3 The MoveIt program can be moved around onscreen when users click the buttons on its interface.

MoveIt consists of the form frmMove, which contains four CommandButtons placed in its corners. When you run MoveIt, clicking one of these buttons will move the form to the corresponding corner of the screen. In the center of the form is a label that will provide event notification--in other words, it will report information such as mouse movement and which button has the focus.

Create MoveIt (general steps)

1. Create the graphical user interface (GUI).

2. Program the Form_Load() event procedure.

3. Program the Click() event procedures.

4. Add the event notification.

Creating the Interface

Create MoveIt's GUI

1. Create a new project by choosing New Project from the File menu. Select Standard EXE from the New Project dialog.

2. In the Properties window, change the name of the project's form to frmMove. (You can call it something else if you want, but make sure that you're consistent.)

3. Add four CommandButtons to frmMove's corners and add a label in the center. You don't have to position the buttons and label exactly because you'll later put them in the proper locations by using code.

4. In the Properties window, name the label and the four buttons according to Figure 6.4.

FIGURE 6.4 Remember, you can add controls to a form by double-clicking them in the ToolBox.


Form_Load() event procedure naming

Whereas the event procedures for controls are named by joining the names of the object and the event with an underscore character, forms are different. No matter what you name your form, Visual Basic will always use the generic name Form instead of the name you choose. For example, even though the form in this example is frmMove, the name of the Load event procedure is Form_Load().


5. Now set the BorderStyle property of the form to 1-Fixed Single. This ensures that the form can't be resized while the program is running. Also, set the label's Alignment property to 2-Center and its BorderStyle property to 1-Fixed Single to give the label a finished appearance.

6. Save the form and the project, using friendly names such as frmMove.frm for the form and MoveIt.vbp for the project.

Programming the Form_Load() Event Procedure

You can use the Form_Load() event procedure to prepare the form before showing it onscreen when your program is run. You will use this procedure to

Open the Code window for the Form_Load() event procedure by double-clicking anywhere on the form except the buttons, label, or title bar. Then, enter the code in Listing 6.1, being careful to change the names if you named your control differently.


Commenting the code

You don't have to type in the comments (lines that start with the apostrophe (`)) because these lines are for your information only. Be sure to read them, though.


LISTING 6.1  The Form_Load() Event Procedure Code for MoveIt

01 `Set the Caption property of the CommandButtons
02 cmdTopLeft.Caption = "Top Left"
03 cmdTopRight.Caption = "Top Right"
04 cmdBottomLeft.Caption = "Bottom Left"
05 cmdBottomRight.Caption = "Bottom Right"
06
07 `Clear the initial text of the label
08 lblNotify.Caption = ""
09
10 `Set the form's title bar text
11 frmMove.Caption = "MoveIt"
12
13 `The rest of the code centers the form on the
14 `screen, sets the position of the four
15 `CommandButtons, and sets the size and
16 `position of the label.
17
18 `Center the form on the screen. This works by
19 `setting the Left side of the form to the center
20 `of the screen, less half the width of the form.
21 `Also, the Top of the form is set to the center
22 `of the screen, less half the height of the form.
23 frmMove.Left = (Screen.Width - frmMove.Width) / 2
24 frmMove.Top = (Screen.Height - frmMove.Height) / 2
25
26 `Set the Left edge of the buttons. The 200 setting
27 `for the left buttons sets a space between the edge
28 `of the form and the buttons. The right buttons are
29 `set by subtracting the width of the button from
30 `the width of the form, and subtracting 300 to
31 `set a space between the button and the form edge.
32 cmdTopLeft.Left = 200
33 cmdBottomLeft.Left = 200
34 cmdTopRight.Left = _
frmMove.Width - cmdTopRight.Width - 300
35 cmdBottomRight.Left = _
frmMove.Width - cmdBottomRight.Width - 300
36
37 `Set the Top edge of the buttons. This is done
38 `similar to setting the Left edge.
39 cmdTopLeft.Top = 200
40 cmdBottomLeft.Top = _
frmMove.Height - cmdBottomLeft.Height - 500
41 cmdTopRight.Top = 200
42 cmdBottomRight.Top = _
frmMove.Height - cmdBottomRight.Height - 500
43
44 `Set the size of the label
45 lblNotify.Height = 360
46 lblNotify.Width = 3000
47
48 `Center the label within the form. This is done
49 `similar to centering the form.
50 lblNotify.Left = _
(frmMove.Width - lblNotify.Width) / 2
51 lblNotify.Top = _
(frmMove.Height - lblNotify.Height) / 2 - 200

Figure 6.5 shows what the IDE will look like when you enter this code into the Code window. Setting these starting values is called initialization.

FIGURE 6.5 You write event procedures by adding code to the code window within the IDE.

Programming the Click() Event

We'll use the Click() event procedure to move the form around the screen. To do so, double-click a CommandButton to view the Code window. Then, enter that part of the code from Listing 6.2 that applies to that CommandButton. Note that you don't have to enter the first and last line, because Visual Basic already creates that part of the event procedure. (Again, you don't have to type the comments.) For example, you only have to add lines 8 and 12 to the cmdBottomLeft_Click() event procedure.


The Screen object

As you add the code for the Form_Load event procedure, notice a reference to an object called Screen. The Screen object refers to your monitor screen. For a detailed description of the Screen properties, read the online documentation that comes with Visual Basic.


LISTING 6.2  The Click() Event Procedures for the CommandButtons

01 Private Sub cmdBottomLeft_Click()
02
03 `Set the value of the form's TOP property
04 `to the bottom of the screen but bring
05 `it up the height of the screen so that the
06 `bottom of the form is on the bottom of
07 `the screen
08 frmMove.Top = Screen.Height - frmMove.Height
09
10 `Set the value of the form's LEFT property
11 `to the far left of the screen.
12 frmMove.Left = 0
13
14 End Sub
15
16 Private Sub cmdBottomRight_Click()
17
18 `Set the value for the form's TOP property to
19 `the bottom of the screen, but bring the TOP
20 `up the HEIGHT of the form so that the bottom
21 `of the form is on the bottom of the screen.
22 frmMove.Top = Screen.Height - frmMove.Height
23
24 `Set the value of the form's LEFT property to
25 `the right of the screen but bring it across
26 `the screen the width of the form so that the
27 `right side of the form is on the right
28 `side of the screen
29 frmMove.Left = Screen.Width - frmMove.Width
30
31 End Sub
32
33 Private Sub cmdTopLeft_Click()
34
35 `Set the value of the form's TOP property
36 `to the top of the screen.
37 frmMove.Top = 0
38
39 `Set the value of the form's LEFT property
40 `to the left of the screen.
41 frmMove.Left = 0
42
43 End Sub
44
45 Private Sub cmdTopRight_Click()
46
47 `Set the value of the form's TOP property
48 `to the top of the screen.
49 frmMove.Top = 0
50
51 `Set the value of the form's LEFT property to
52 `the right of the screen but bring it back across
53 `the screen the width of the form, so that the
54 `right side of the form is on the right
55 `side of the screen
56 frmMove.Left = Screen.Width - frmMove.Width
57
58 End Sub

Moving the form to the top or left of the screen is easy--set the Top or Left property of the form to zero. This always corresponds to the top or left of your monitor, respectively.

Lining up the form on the right side or bottom of the screen is a little harder because right and bottom properties don't exist. To place a form on the right side of the screen, you must set the Left property of the form to the Width property of the Screen object, minus the Width of the form (because the Width of the screen would be the right property of the screen, if the right property existed).

A similar technique is used to determine the bottom of the screen. If you were to set the form's Top property equal to the screen's Height property, you wouldn't see the form because it would be just below the bottom of the screen. To set the bottom of the form to the bottom of the screen, you subtract the value of the form's Height property from the value of the screen's Height property. This raises the form so that you can see it (see Figure 6.6).

Adding Event Notification

To finish MoveIt, let's add some code that will tell when certain events occur for the form and the CommandButtons. When users press or release the mouse button over the form, the text in lblNotify will change to reflect the state of the button. Also, when users use the Tab key or the mouse button to move from one CommandButton to another (which changes the focus from one button to the next), the text in lblNotify will change. Doing this requires you to write code in three different event procedures: the MouseUp and MouseDown event procedures for the form and the GotFocus event procedure for each CommandButton.

FIGURE 6.6 Be careful when placing a form on the right side or bottom of the screen; otherwise, you might place it offscreen.

Enter the code from Listing 6.3 into the MouseUp and MouseDown event procedures for frmMain. (Remember that you don't have to enter the first and last lines.) To do this, open the Code window for the MouseDown event procedure by double-clicking the form and selecting MouseDown from the event procedures drop-down list (see Figure 6.7).

LISTING 6.3  Code for Reporting When Users Click and Release the Mouse Button

01 Private Sub Form_MouseDown(Button As Integer, _
Shift As Integer, X As Single, Y As Single)
02
03 lblNotify.Caption = "MouseDown Event"
04
05 End Sub
06
07 Private Sub Form_MouseUp(Button As Integer, _
Shift As Integer, X As Single, Y As Single)
08
09 lblNotify.Caption = "MouseUp Event"
10
11 End Sub

FIGURE 6.7 You can select an event procedure from the object's Code window.

When the program runs, if your mouse is over the form (not the CommandButtons or the label) and you click the mouse button, the text MouseDown Event appears in lblNotify. When you release your mouse button, the text MouseUp Event appears.

Last, add the code that will report which CommandButton has the focus. Enter the code from Listing 6.4 into the GotFocus event procedures for each CommandButton. Do this by double-clicking one of the CommandButtons and selecting the GotFocus event procedure (notice that Visual Basic selects the Click event by default). Repeat this procedure for each CommandButton.

LISTING 6.4  Code for Reporting Which CommandButton Has the Focus

01 Private Sub cmdBottomLeft_GotFocus()
02
03 lblNotify.Caption = "cmdBottomLeft has the Focus"
04
05 End Sub
06
07 Private Sub cmdBottomRight_GotFocus()
08
09 lblNotify.Caption = "cmdBottomRight has the Focus"
10
11 End Sub
12
13 Private Sub cmdTopLeft_GotFocus()
14
15 lblNotify.Caption = "cmdTopLeft has the Focus"
16
17 End Sub
18
19 Private Sub cmdTopRight_GotFocus()
20
21 lblNotify.Caption = "cmdTopRight has the Focus"
22
23 End Sub

That's it! Now you can run the program--just press the F5 key (see Figure 6.8).

FIGURE 6.8 When you click a CommandButton, it automatically receives the focus. In MoveIt, the focus is reported in lblNotify.


Previous chapterNext chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.