During this hour you will learn
This lesson puts action into the controls you learned about in Hour 3's lesson. Although your first application has several nice-looking controls, the controls don't do anything. You'll add code behind the controls this hour to activate those controls so that something happens when users use one of the controls.
In this hour, you'll gain some insight into the Visual Basic language. When you activate a control, you do so with VB programming code. The code goes in a special program section called an event procedure. If you've written an event procedure for a certain event, such as a mouse click, the code inside that event procedure executes.
Each control has its own set of events that the control supports. You can probably predict many control events. For example, one obvious command button event is the click event, called appropriately enough, Click. Even forms have their own set of events such as Click, DblClick, Resize, and so on. As you become more familiar with events, you'll learn which events go with certain controls.
FAST TRACK |
Are you familiar with Windows events? If so, move to the next topic section, "Event Procedures", to learn how to implement event controls in Visual Basic. |
Almost anything users can do on a form or with controls on a form is an event. A huge number of events exist simply because of the huge number of user possibilities. Not only does an event occur when you move your mouse but also when you drag your mouse. Some actions trigger multiple events. When you double-click your mouse, a single click occurs then as well and a mouse up event occurs when you release your mouse button.
Visual Basic must be able to distinguish among various similar and different events so that Windows passes as many detailed events to your program as possible. Your program can respond to none, some, or all events. Rarely will you ignore all events or handle all events that Windows passes to your program. Instead, you'll handle those events that apply to your program, and the form and controls in your program,, and you'll ignore the rest.
Not all events are user-triggered. In Hour 23's lesson, "Enhancing Your Program," you learn that your computer's internal clock triggers an event at every tick.![]()
The following sections explain some of the events possible with the form and the three controls you've added to Hour 3's application.
These sections review only the bare-bones fundamental and most common events. When you learn how to deal with these events, you'll have no trouble accepting additional events described throughout the rest of this night-school tutorial.![]()
Generally, you don't capture very many form events in applications. Often, the form events that you deal with are the events that occur when your user starts or quits your application. Here's a list of common form events:
Although almost every application you create will contain one or more command buttons, the command button doesn't support as many events as most of the other Visual Basic objects, such as forms and text boxes. The command button is simpler than many of the other controls.
Here's a list of common command button events:
Labels usually are dormant and simply display text such as titles and instructions. Users can't enter text in a label or change the label's text directly. (The label's text changes only through Visual Basic programming code.) Labels can be the result of an event, however. Here's a list of common label events:
You'll see in the next topic section that the Image control displays graphic images. Although your sample application has yet to do anything with its image, such as make the image display a picture, you can probably imagine that the Image control supports several events. After all, the Image control is a lot like a Label control, except that the Image displays a graphic image and not text.
Here's a list of common Image control events:
Almost any event that you want triggered can be triggered. Both keyboard and mouse users can trigger many of the keyboard and mouse events. Consider, for example, the number of ways you can trigger the Click event. You already know that the Click event occurs whenever users click the left mouse button. The Click event also can occur in response to a number of other events:
The active control on the form is the one with the focus. You'll learn more about focus in this lesson's third topic.
If you see an underlined letter in a command button's caption, you know that you can "click" the command button by pressing the Alt key along with the underlined letter. The ampersand (&) before any character in a caption specifies that character as the shortcut character. The user won't see the ampersand in the label's caption but will see an underlined letter instead.
As with the control properties, you'll learn many control events just by using Visual Basic. The true goal of your application hasn't yet been revealed to you, but you've probably almost figured out what the application will do, especially after you add the suggested names from last hour's lesson.
This hour you'll set up your application to display a happy face in the image area when users click the center command button. Figure 4.1 shows what the finished application will look like when users click the command button.
The application displays the happy face when users click the command button.
Visual Basic comes with several graphic images. The happy face is actually an icon that you'll stretch to the Image control's measurements.![]()
Obviously, you're going to have to handle the command button's Click event. The label doesn't need to respond to any events, and neither does the image. (This application is staying fairly simple because you're still new to Visual Basic.)
Visual Basic supports a special mechanism for handling the events you want to handle and for ignoring all the others. You'll have to see some Visual Basic programming code first, and then learn how to complete this application in the next topic section.
Before moving onto event code, give your application's command button the Alt+C shortcut keystroke-in other words, change the Caption property to read &Click Here. As soon as you type the caption, you'll see that the command button's first letter is underlined, indicating the shortcut keystroke's designation.
Any letter, not just the first letter, can be a command button's shortcut key. You can also apply shortcut keystrokes to other controls, such as option buttons and check boxes.![]()
Your application can use the Load form event. When Visual Basic loads the form, you can request that Visual Basic center the form inside the screen's coordinates automatically.
You used the Form Layout window last hour to center the form within the screen's boundaries. However, Visual Basic can position the form more accurately within the screen's coordinates and can even center the form, no matter what kind of monitor end users have.
The users' screen is a special fixed object that's always available to your Visual Basic program. Your program can access the screen by using the Screen object name. As with Visual Basic controls, the Screen object has properties that you can access. Two helpful Screen properties are Width and Height. By calculating the center of the screen from the Screen's Width and Height properties, you'll ensure that Visual Basic will center your form on every computer your application runs on. The next topic section centers the form through Visual Basic code.
Windows sends to your application all events that apply to your application. Handling or ignoring Windows events requires only that you
This topic describes what event procedures are, how to specify them, and how to implement event procedures in your sample application.
FAST TRACK |
Have you written Visual Basic code before? If so, skip down to this topic's example section to learn about Visual Basic 5's Auto Quick Info pop-up help. You'll wish you had that feature sooner! |
An event procedure contains Visual Basic code. The Visual Basic code describes the instructions that your computer is to follow when the event occurs. For example, if you write an event procedure for the command button's Click event, Visual Basic executes that event procedure only if users click your application's command button. If users never click the command button, the event never occurs, and the code in your command button event procedure never executes.
Before looking at event procedure specifics, look back at the preceding topic section's event lists. Notice that the form, command button, label, and image all support the Click event. In other words, if users click the mouse over any of these four objects, a Click event occurs. Your program, however, must know which control (or form) users were clicking over.
Remember that every handled event requires an event procedure. The event procedure name is a special name that not only names the event handled, but also the control name that received the event. All event procedures have names; the names describe both the control and event that produced the event.
Here's the format of event procedure names:
ControlName_Event ()
If you want to write an event procedure for a mouse click over the command button, you would name that event procedure cmdGetHappy_Click (). The underscore separates the control name from the event.
The parentheses aren't actually part of the event name, but you'll always see parentheses after every event procedure name. The parentheses are often empty, but they sometimes hold items that you'll learn about as you progress through your Visual Basic night-school training.![]()
Therefore, in the application you're creating, if users click the command button that you've named cmdGetHappy, the application will execute any code you've stored in an event procedure named cmdGetHappy_Click (). If you don't write the event procedure, however, your application would do nothing when users click the command button.
You must know the control's exact name (through its Name property listed at the top of the Properties window as (Name)) and the name of the event you want to handle if you want to know the name of that control's event procedure. Fortunately, Visual Basic can automatically generate event procedure names for you, as you'll see in a moment. Thus, you don't even have to type the special event procedure name because Visual Basic generates the name for you and automatically separates the control name from the event with the required underscore character.
Here's the complete event procedure that you'll add to your application's command button:
Private Sub cmdGetHappy_Click() imgViewHappy.Picture = LoadPicture("C:\My Documents\ [ccc]VB NightSchool\Happy.bmp") End Sub
The code is only three lines long, and the first and last lines really do nothing more than identify the event procedure's starting and ending points.
Indent the body (the code lines between the first and last lines) of event procedures so you can quickly locate executable code from a listing of event procedures.![]()
Almost every event procedure that you write will begin with Private Sub. The Private keyword is optional; if you don't specify Private, Visual Basic assumes that the event procedure is private anyway. By specifying Private, however, you clarify your intention to leave the procedure as a private procedure. When a procedure is private, only other procedures within the current module has access to the procedure.
Visual Basic supports two kinds of procedures: functions and subroutines. Although both look similar, they vary in how they terminate. A function, indicated by the Function keyword, always returns a value back to somewhere. Subroutines, indicated by the Sub keyword, don't return values. A control's event procedure doesn't return a value, so control event procedures are subroutines. Hour 13's lesson explains the differences between subroutines and functions in much more detail.
A keyword is a built-in Visual Basic language command or routine. When programming, as you'll learn in this book's second part, you often need to assign names to various program elements. You can't assign keywords to your own program elements.![]()
The name of the subroutine, cmdGetHappy_Click tells you that this subroutine is the command button's cmdGetHappy click event procedure. The event procedure executes only when users click over the command button named cmdGetHappy. If this is the only event procedure in the entire application, the application will ignore all other events that Windows passes to the application. Therefore, if users move the mouse over the command button or clicks on the label or the image control, the program will ignore these events sent to it.
Event procedures can range from one to several hundred lines. Generally, event procedures are short, from three to 10 lines. If an event procedure grows to more than 20 or so lines, most Visual Basic programmers will break up the event procedure code into external smaller procedures and trigger those procedures from within the event procedure.
This event procedure's body is only one line long. Not much has to happen when users click the command button. During design time when you write the program, the image control's Picture property stays blank (indicated by (None) in the Properties window). When users click the command button, the Image control displays the happy face, a bitmap graphic image that comes with Visual Basic.
Notice how you specify properties in Visual Basic code. Type the control name, followed by a period, followed by the property name. Therefore, imgViewHappy.Picture refers to the Picture property for the control named imgViewHappy. If the form contained another Image control, the other control wouldn't be affected by this line.![]()
If you were to assign a picture to an image at design time, you can type the path name and bitmap file name into the Properties window's Picture property. However, if you want to assign a bitmap picture to the Image control at runtime, you must use the LoadPicture() built-in function. Remember that functions return values, and the LoadPicture() function returns a bitmap image. The end result of the event procedure's middle line is the loading and assignment of the picture to the image. As soon as the assignment takes place (when users click the command button), you see the image on the running form.
You must assign the full path name of the Happy.bmp file to the file's location on your own disk; otherwise, the application won't find the bitmap. Therefore, change LoadPicture()'s path name from this lesson's \My Documents\Visual Basic NightSchool directory folder to the location of Happy.bmp on your computer. You can use the Windows Start menu's Find command to locate the file. If the file is buried deeply inside multiple directories (as is probably the case), you should copy the file to a simpler location.![]()
Visual Basic must know where your event procedure ends. All subroutine procedures end with the End Sub statement (a code line); all function procedures end with the End Function statement. The command button event procedure is a subroutine, hence the termination of the code with End Sub.
You'll create this event procedure (with your computer's Happy.bmp's path name) in the example that follows the next section.
Now you understand the event procedure. But how and where do you enter the code? Visual Basic makes it easy. VB uses a Code window to hold code that you write and edit. The Code window contains Visual Basic's editor. Figure 4.2 shows an example Code window. As with most windows, you can resize the window and place it where you want it to appear.
Enter and edit VB code inside the Code window.
The Code window's editor works like a word processor, except that the editor doesn't wrap lines of text. You need to press Enter at the end of each line of code that you type. You can insert and delete text just as you can inside word processors, and the Windows Clipboard operates as you expect. If your line gets too long to read inside your Code window, put an underscore at the end of the line and continue the statement on the next line.
To complete the application with the happy face, you first might want to locate and move the Happy.bmp file to your application's disk location, if you haven't already done so.
Also, you must modify one Image control property that isn't set properly for this application. By default, the Stretch property is set to False. If you leave the Stretch property set to False, the happy face won't stretch to the control's full size but will appear as the bitmap's actual size, which is much smaller than the control. Change the Stretch property value to True. When the image subsequently displays the happy face, Visual Basic stretches the happy face to the size of the Image control's boundaries; the happy face appears on your application's form stretched larger than its disk image.
After you change the image's Stretch property to True, you must add the event procedure for the command button's Click event in the Code window. To open the Code window from the Form window, simply double-click the form's command button. Visual Basic opens the code editor shown in Figure 4.3.
Complete the event procedure with the Code window.
One of the truly nice things about the Code window is that Visual Basic automatically writes the first and last lines of the event procedure for you and opens a space for the body of the code. Type the following line between the first and last lines (be sure to insert your own path name) to complete your application's single event procedure:
imgViewHappy.Picture = LoadPicture("C:\My Documents\ [ccc]VB NightSchool\Happy.bmp")
When you type the LoadPicture()'s opening parenthesis, Visual Basic displays Auto Quick Info pop-up help (see Figure 4.4). Whenever you type the first part of a built-in routine or keyword, Visual Basic displays Auto Quick Info to describe the entire statement's format. For the LoadPicture() function, Auto Quick Info tells you that the center part must be a file name, followed by an As clause. (The As clause turns out to be optional, because Visual Basic assumes the correct clause for you.)
Visual Basic helps you complete program statements.
Auto Quick Info's help
Because Visual Basic is a fairly large programming language, the Auto Quick Info feature comes in handy, especially if you need to use some obscure functions and don't remember the exact format of the functions.
How did the Code window know that you needed the Click event procedure and not DblClick, MouseMove, or any of the other event procedures that you could write for the command button? When you double-click any control on the Form window, Visual Basic opens the Code window and writes the first and last lines for the most common event that takes place for that control. The most common event that a user performs on a command button is the Click event. If you double-clicked on the Form's background rather than the command button, the Code window would display the Form_Load() event procedure, the most common event programmed for forms. If you want to write an event procedure for an event that isn't the Click event, you have to select that event from the Code window's drop-down list of events (see Figure 4.5).
Select the event for which you want to write an event procedure.
Close the Code window and run your application. You'll see the Form window you're now used to. Click the command button and watch the happy face appear. Congratulations! You've written your first event-driven Visual Basic application!
If you get an error dialog box that looks something like the one in Figure 4.6, you haven't set the happy face bitmap image's path name properly inside the event procedure's code. (You've just written your first Visual Basic bug.) ClickEnd to terminate the error message and program and correct the path name. Use Windows Explorer or the Windows Find command if you need help finding the exact location of the file named Happy.bmp. If the Code window doesn't appear when you close the error's dialog box, return to the Code window to fix the bug by choosingCode from theView menu or by double-clicking the command button again.
A bug appears in the application.
Just for fun, run the program again. But rather than click the command button, press Alt+C to display the happy face. Alt+C is the shortcut key for the command button. As explained earlier in the section "Triggering Events," a command button's shortcut key triggers the same event as clicking the command button.
Now add a second event procedure to the application. Follow these steps to make the form automatically center itself on-screen, no matter what kind of graphics adapter or screen size users have:
The Code window holds all your event procedures.
frmMyFirst.Left = (Screen.Width - frmMyFirst.Width) / 2
Let the Auto List Members drop-down list help you locate properties.
frmMyFirst.Top = (Screen.Height - frmMyFirst.Height) / 2
You can save time by omitting the form name from the form's event procedure body. The following two lines are identical to the ones you typed for the form load's event procedure:
Left = (Screen.Width - Width) / 2 Top = (Screen.Height - Height) / 2
By specifying the form name, however, you lessen ambiguity in your code but have to type more to finish the procedures.
Again, don't worry about the specifics of this code just yet. Although you can probably figure out what the code is doing, subsequent lessons will explain all the details for you.![]()
Save your application. The final topic in this lesson will add one additional item to the application.
Now that you're mastering the placement of controls and their event procedures, you have a jump-start on the rest of your Visual Basic learning. Although each of the remaining Toolbox controls varies from the Label, Command Button, and Image controls, you place them on the Form window by using the same steps you place the other controls. You also can write event procedures for them in the same manner as the controls you now know. This topic section concludes this hour's lesson by introducing you to the Text Box control and explaining how to manage a form's focus.
Whereas users can't type values directly onto a Label control, the Text Box control allows data-entry by users. When you want your user to enter a name, address, or other word or phrase, place a text box on your form. The Text Box control can display initial default text, or you can leave it blank for the users. You also have a choice how the text appears in a Text Box control.
As you begin to place additional controls that require user interaction, such as command buttons and text boxes, you have to begin determining the form's Tab order or focus. When users execute the application, they can press Tab to move the highlight from control to control. The control now highlighted is said to have the focus, and all applications have at least one control in focus at any one time (if the application contains user-input controls, such as command buttons and text boxes).
Text Box controls work like interactive labels; you display text in text boxes, but users can change or enter entirely new text. Also, users can leave your original Text Box control text, so your program can continue working with the default text.
Don't use text boxes for asking users yes/no questions. You'll use input boxes for such questions when you get to Hour 9's lesson.![]()
The Text Box control properties are important for understanding how Text Box controls work. Read through these common Text Box control properties that you'll work with:
When you design text boxes, you must decide whether you want users to have multiline capabilities. If you want the text box to hold multiple lines of text (via a True MultiLine property), you should also set the ScrollBars property to one of its possible values. The scroll bars let users move back and forth between the Text Box control's lines of text.![]()
The Text Box control has no Caption property. The Text property holds the text that users initially see.
Here are some common Text Box control events that you'll frequently use:
Be sure to label your text box to tell users the information you want in the Text Box control. Don't just put an unlabeled text box on a form and expect users to know what to type.![]()
One control on your form will have the focus, and user actions can move the focus to other controls. The focus is the currently highlighted control. Some controls, such as labels, can't receive the focus, but any control that interacts with users can receive the focus.
Figure 4.9 shows an application similar to yours that contains three command buttons. Notice that the third command button has the focus because of the dashed box around the control. Pressing Enter, therefore, would "click" the third command button. If users press Tab, another command button would receive the focus and the highlight would move to that command button.
The focus moves between controls.
Highlight indicates current focus
Why do you think Figure 4.9's third command button uses the letter a as the shortcut key and not the letter S? You should not give two or more controls the same shortcut key. The second command button already uses the S, so the third command button had to use a different letter. If you give two or more controls the same shortcut key, the key with the lower TabIndex property will always receive the shortcut keystroke.![]()
The TabIndex property determines the focus order. Visual Basic automatically uses 0 for the TabIndex of the first control you place on the form, 1 for the second control you place, and so on. When users run the application, a Tab press sends the order through the controls determined by the sequential TabIndex values. Changing the TabIndex sequence changes the order of the focus.
Some controls can't receive the focus, but you can still set a TabIndex property for those controls. The TabIndex property simply sends the focus to the next control in line for the focus.
Give your text boxes a TabIndex value that's one less than the label that describes the text box. If you assign a shortcut key to the label, users can press the label's shortcut key to jump to the text box. Labels can't receive the focus, so the label sends the focus (obtained by the shortcut key) to the next control in line to receive the focus, which will be the text box.![]()
Until now, you've had to exit your application by clicking the application's Close window button in the upper-right corner of the form. Clicking the Close window button isn't an elegant way to terminate a running program, however. This example adds an additional command button that you can use to exit the program.
Follow these steps to add the command button and set up the application to respond to the new command button:
The new command button gives you an exit.
Windows programs rarely have such an exit command button. Generally, standard Windows programs use theFile menu's Exit command for the program's exit. Hour 5's lesson, "Creating Menus for User Ease," explains how to add menus to your applications.![]()
Load and run the sample application named Controls that comes with Visual Basic. (You should find the Controls project inside Visual Basic's \Samples\PGuide\Controls directory.) The sample application demonstrates single-line and multiline text boxes extremely well. When you run the application, click the command button labeled Text Box; Visual Basic displays the window shown in Figure 4.11.
Practice with the sample Text Box control.
The sample application demonstrates that you can, through Visual Basic programming, manage the location of the Text Box control's text cursor (often called the insertion point or caret), select text, and restore saved text.
Type several lines of text into the sample's multiline text box, and you'll see why scroll bars come in handy. To see the text toward the top of the multiline text box, you have to press the up-arrow key several times to scroll back up when you don't have scroll bars.
Also, if you have a large monitor (at least 17 inches), you'll see why centering forms is a good idea (the Controls project fails to center the form).![]()
In this hour, you learned how to activate your controls. By entering code into event procedures with the Code window, you can set up your controls to respond to one or more events. Visual Basic helps get you started by writing the first and last line of your event procedures. If you double-click over a control, Visual Basic takes you to that control's default event procedure, but you can select from the event's drop-down list if you want to work with another event for that control.
As you begin to improve the power of your applications, you need to worry about the focus order of the controls. Users rely on the focus order so that they can use the keyboard rather than the mouse to step through the controls at times. You should place the first focus on the control that users will most likely select and use first.
In Hour 5, you'll learn how to add menus to your application. Visual Basic creates menus that add a professional Windows appearance to your applications.