Visual Basic in 12 Easy Lessons vel04.htm

Previous Page TOC Next Page



Lesson 2, Unit 4


Bare-Bones Programs



What You'll Learn


In this unit, you will create your own program with Visual Basic from scratch You will write a fully-working Windows program that displays a resizable window, a command button, and a control button with a control button menu.

Before you create your first application, however, you must understand how Visual Basic programs interact with the Windows environment.

Event-Driven Environments


Concept: A Windows program behaves differently from a DOS-based program. Instead of the program controlling the user, the user controls the program. When the user responds to a menu or control, Windows generates an event that describes the particular action.

Picture yourself driving down the road. All kinds of controls are at your fingertips—steering wheel, blinkers, headlights, breaks, gas pedal, gear shift, radio knobs, rearview mirror, and air conditioning and heater controls. At any time, you might press the brake, turn left, turn on the radio, adjust the mirror, or speed up. The driving conditions, not the physical order of the controls, determine what you do next.

When you press the gas pedal, does your foot alone make the car go faster? The answer is no. You would have to have a very powerful foot to be able to speed up a car already going 50 miles per hour. The foot pedal causes an event to happen. That event is that more gas is fed to the car for fuel to burn and the car goes faster. Your car performs its job and makes adjustments based on the events that you trigger.



Definition: An event can be a mouse move, a mouse click, a keystroke, or a control response.

Using a Windows program is like driving a car in the following respect: You do not always perform the same actions, and the actions that you perform cause certain events to occur. In Windows terminology, an event is the action that the user takes. Whenever the user clicks the mouse, presses a key, responds to a control, or selects from a menu, an event happens. Windows constantly monitors the running Visual Basic program, looking for events.



Note: Too many things can happen in a GUI-based program for it to follow a straight, sequential pattern. If you were to run a DOS-based accounting program, the program more than likely would present you with a menu of limited choices. Only after you select from the menu, does the program take you through the next step. In a Windows program, you are offered a selection of controls, and you can respond to any control in any order. The program must be able to sense when an event takes place and to handle it accordingly.

Windows and Visual Basic constantly monitor running programs. When the user clicks a command button or performs any other kind of event, Windows intercepts the event and sends it to Visual Basic.

Visual Basic does not respond to some special system events, such as when the user presses Alt+Tab to switch to another application running in memory. That is why Windows must interpret all events and pass the ones handled by Visual Basic to Visual Basic. Figure 4.1 shows the relationship between events and event procedures. Notice that Windows always intercepts the events and passes the appropriate events to the Visual Basic program, where Visual Basic then does something in response to them if event procedures are available.

Figure 4.1. Windows intercepts events before it passes them to Visual Basic.



Definition: An event procedure responds to an event.

When Visual Basic gets an event from Windows, it checks whether the programmer wrote an event procedure for the event. If an event procedure exists, Visual Basic executes the event. In the CONTROLS.MAK program that you ran in the previous unit, clicking the Next Control command button caused the next control in the program's repertoire of controls to appear. The only way that the program could respond to the Next Control command button was for an event procedure to be written for that particular event—namely, the command button keypress.

A program can contain controls and still not respond to all events. In CONTROLS.MAK, for example, when you select the check boxes, nothing happens except that the boxes are selected or deselected. The check box controls handle the checking and unchecking of the boxes so that no event procedure is needed to do that. Once you select check boxes, though, the program does absolutely nothing with the selected check boxes because there is no event procedure inside CONTROLS.MAK that does any work when the user selects a check box. The check boxes exist in that program only to illustrate how they operate.



Warning: Most, but not all events, are user-triggered. Some internal Windows events can take place that trigger actions. Likewise, you can direct a program to respond to timed intervals, such as ticking a clock forward every second. The interval of time would be an event in that case.

Is all this talk about events and event procedures getting technical? Actually, you will see that the implementation of event capturing and event procedures is extremely easy. The Visual Basic environment is set up to create event procedures for you when you request them. The bottom line is this: When you want your Windows program to respond to an event, make sure that you write an event procedure for it. If you want to ignore certain events, don't write event procedures for them.



Tip: Most of the events that you want to handle are obvious. For example, if you add a command button control to a form, you want to do something when the user clicks the command button. However, if the user tries to drag the command button with the mouse, you probably want to ignore that event because the user should rarely be allowed to move controls during the execution of the program.

Review: Almost anything that can happen during the execution of a Windows program can be an event. Once you design a Windows program form and place controls on it, you must write code that responds to events. That code is made up of event procedures. In a way, each event procedure is like a miniature program that you write for each control whose event should cause an action to take place.

Control Properties


Concept: All controls are different and work differently. You use different controls for different things. Even among controls of the same type, however, differences exist. Those differences reside in the control properties.



Definition: A property determines how a control differs from other controls.

Consider the three controls shown in Figure 4.2. All three controls are command buttons even though they all look different. The user can click any of them, but each has a different set of properties.

Figure 4.2. Three command buttons with different properties.

The top command button has the size seen most often in Windows programs. Visual Basic automatically assigns this size when you add command buttons to your applications unless you specify something different. The second command button is much wider than the top one, and no access keystroke is available. Its caption is not displayed in boldfaced letters, and the font is not standard. The third command button is very small, and its caption is italicized. Because small italics on command buttons are not always easy to read, be careful about using them with small controls.



Tip: Less is usually better.

Adding too much of anything is usually worse than better. The application often requires that command buttons differ from their default size, but try to stay as consistent as possible. It is rarely a good idea to put more than one font on more than one command button that appears on the same form.

One of the most important steps you take when you write Visual Basic programs is setting control properties. When this book teaches you how to add a new control to an application, you will learn about virtually all of its properties. The next unit, for instance, shows you how to place command buttons. Before you learn about placement, though, you will read about the command button's 25 properties.



Note: Rarely will you have to change all the properties of a control when you place the control on the form. Nevertheless, if you see every property that is available when you learn a new control, you will know what you can—and cannot—do it.



Even Forms Have Properties: Visual Basic programmers use the generic term object for controls that they place on the form. Actually, even the form is an occurrence of an object. The word object means different things in different computer languages. Although faintly related, a Visual Basic object has little to do with the objects that you find in object-oriented programming languages such as C++.
Every object in a Visual Basic program has properties. Even the forms have properties. As you can see from Figure 4.2, you can add descriptive titles to forms. The title of a form is one of its property settings. The background color is another property that you can set. Although you should stick to forms with white backgrounds for the sake of consistency—it is used for most Windows programs—you, the programmer, can change it.




Tip: Where do you add properties for controls?
In the Properties window. (Good name, huh?)


Review: Each control has a different set of property values. You often set initial property values when you place controls on the form. During the execution of the program, your code also often changes property values. The CONTROLS.MAK application, for example, changes a command button's caption property from Press Me to Once Again and back to Press Me. I added the original Press Me caption when I added the command button to the form. Then I used code to change the caption during the program's execution. What enables Visual Basic to know when to change the caption? When the user presses the command button, a command button click event occurs. Then the event procedure written for that particular event changes the caption. Read on, true Visual Basic believer, and you will see that event procedures are neither as difficult, nor as complicated, as they might first sound.

Naming Conventions


Concept: Although you will learn all about control properties throughout this book, one control property is worth learning about early on—the Name property. All controls have a Name property. The Name property labels each particular control. Without a unique name, you could not distinguish one control from another inside the Visual Basic code. Although Visual Basic assigns default names to all controls, get in the habit of changing those names to something more descriptive so that you can remember them more easily as you add to the program.



Definition: A naming convention is a set of naming rules.

The first property that you should always set is the Name property. This unit does not tell you how to set the Name property; that is covered in the next lesson. You must know in advance, however, that Visual Basic programmers do not arbitrarily assign names to controls. Programmers who want to make their programming lives less stressful follow prescribed naming conventions when they choose names for their controls.

A convention is not just a group of people gathered for the weekend. A convention is a standard set of rules that you follow. You are already familiar with naming conventions—for example, the file-naming conventions used in Windows and DOS-based computers (up to eight characters for the name and up to three characters for the extension). In Visual Basic, the naming convention for controls is simple. When you decide on a name for your control, be sure to stay within these boundaries:



Definition: A reserved word is a Visual Basic command.

  1. [lb] Names cannot be the same as a reserved word. Appendix B lists all the reserved words in Visual Basic.

The following are valid names:

and these are not:

Select is a Visual Basic command. 723 does not begin with a letter of the alphabet. cmdExit&Leave contains an invalid character, the ampersand (&).



Warning: Even though the underscore is a valid character, many programmers prefer not to use the underscore because it sometimes can look like a minus sign.
Many programmers use hump notation—mixing uppercase and lowercase letters in names that contain several words. The term hump comes from a camel's back, which the uppercase letters in the name sort of resemble. For example, cmd_Add_Sales is a valid name, but cmdAddSales is just as readable and it does not contain the underscore characters that sometimes lead to confusion.


Learn these naming conventions well. The naming conventions apply not only to Name properties but also to other aspects of Visual Basic, such as variables and procedures.



Write Once, Maintain Often: Rarely are you finished with a program after you write it. You usually have to update the program to reflect changes in the environment in which you use it. When you update a program already written, you are doing what is called program maintenance.
For example, if you wrote an accounting program for a small company that merged with a second firm, the accounting department might have to keep both companies separate until the current fiscal year ends. You must modify the program so that the program distinguishes between the two companies and keeps two sets of data. The more time you spend giving meaningful names to controls, the less time you will spend later trying to figure out what each control is for. It is obvious that a control named cmdComputeProfit triggers the computation of a profit calculation.


I strongly suggest that you adopt is the standards for naming control prefixes listed in Table 4.1. Table 4.1 shows the three-letter prefix that you should add to the front of a name when you name a control. The prefix describes what the control is. Therefore, from the name itself, you know what kind of control you are working with. Of course, if you placed the control on the form and named the control to begin with, you would know what kind of control you are adding. When you add code to event procedures later, however, the three-letter prefix helps you keep the kinds of controls straight and it prevents you from trying to write an incorrect event procedure for a control that does not produce that particular event.



Note: Table 4.1 lists all the naming conventions for controls and forms, including those controls that you do not know yet.


Table 4.1. Standards for naming control prefixes.

Prefix Control
cbo Combo box
chk Check box
cmd Command button
dir Directory list box
drv Drive list box
fil File list box
fra Frame
frm Form
grd Grid
hsb Horizontal scroll bar
img Image
lbl Label
lin Line
lst List box
mnu Menu
ole OLE client
opt Option button
pic Picture box
shp Shape
tmr Timer
txt Text box
vsb Vertical scroll bar

Here are some control names that use the three-letter prefixes from Table 4.1:

There is a wider blanket of conventions that cover the look and behavior of all Windows programs. The book The Windows Interface: An Application Design Guide, by Microsoft, discusses all the standards. It suggests how you can design your Windows programs so that they behave like other Windows programs.

When users move from DOS to Windows, they often complain that Windows is different and hard to learn and use. They are correct that Windows is different, but there is there is much disagreement on how difficult and hard-to-use Windows is.

Even if you accept that Windows is hard to learn and use, you have to learn the Windows interface only once. That means that after you master a Windows program, such as the Visual Basic programming environment or Microsoft Excel, every other Windows program behaves in almost exactly the same manner. Almost every Windows program contains an Exit command on a File pull-down menu. Almost every Windows program displays the same File Open dialog box. Almost every Windows program displays a white background. Software developers do not have to follow these standards, but users are more likely to learn the programs if they do. The application design guide helps them stay consistent with the standards.

Review: When you name controls, don't assign arbitrary names or even stick to the name that Visual Basic assigns—you won't like Visual Basic's suggestions. Select a name that indicates the purpose of the control, and use one of the three-letter prefixes described in Table 4.1. By following such standards, you will ensure that your program is easier to maintain down the road.

More Consistency: AUTOLOAD.MAK and CONSTANT.TXT


Concept: With the AUTOLOAD.MAK and CONSTANT.TXT files, you can add even more consistency to your Visual Basic programs.

Over time, you incorporate many common elements in your Visual Basic programs. Perhaps you have written a set of routines in the Visual Basic language that you want to make available to several Visual Basic programs. As you already know, by adding files to the project window, you, in effect, add those files to the resulting application.

AUTOLOAD.MAK is a special project file that you can load and look at. If you load the file, you won’t see anything that looks very special. The Form window is empty, and the Project window contains the same two files, GRID.VBX and OLECLIEN.VBX, that you saw earlier when you started Visual Basic and loaded and ran an application.

The purpose of AUTOLOAD.MAK is to create a base application that you add new features to and build on to create another application. In other words, whenever you start creating a new application using the File New Project command, Visual Basic looks at the contents of AUTOLOAD.MAK and creates a new base application that looks just like AUTOLOAD.MAK. Therefore, if you want to change the default behavior of your new applications, load and change AUTOLOAD.MAK. After you change AUTOLOAD.MAK, all future projects that you create will hold those changes.



Tip: Think of AUTOLOAD.MAK as working as how the DOS AUTOEXEC.BAT file works. Whenever you start your computer, DOS looks at the AUTOEXEC.BAT file and starts the computer according to those instructions. Every time you start a new application, Visual Basic looks at AUTOLOAD.MAK and creates a new application with the same features as AUTOLOAD.MAK.

Now take a look at how changing AUTOLOAD.MAK changes all your new projects. Load AUTOLOAD.MAK if it is not loaded, and look at the Project window. Because you won’t need the GRID.VBX or OLECLIEN.VBX files for a while, there is no reason to load them along with all the others every time you create a new application. Once you load AUTOLOAD.MAK, follow these steps to remove the files:

  1. Display the Project window if you cannot see the Project window.

  2. Highlight the GRID.VBX file.

  3. Select the File Remove File command. As soon as you do, Visual Basic removes GRID.VBX from the Project window. The last file in the project, OLECLIEN.VBX, is still highlighted.

  4. Select File Remove File again. Visual Basic removes OLECLIENsx.VBX from the project window.



Note: By the way, your toolbox now contains two fewer controls because the two .VBX files that you just removed contained special controlling tools called custom controls.

If you now saved AUTOLOAD.MAK to the disk, all future projects that you create would look just like the AUTOLOAD.MAK that you now see. Before you save AUTOLOAD.MAK, however, read a little further to learn about another file that you should add to the Project window.



Tip: Add the CONSTANT.TXT file to lighten the rest of your programming burden.



Definition: A named constant is a constant value with a name that is easy to remember.

There will be several times when you have to set various controls to specific values from a list of possibilities. For example, a label control can have a boxed border around it if you set the value of a certain property to 1—a fixed single-line border—and no border if you set it to 0. Instead of setting properties with those hard-coded values, you can use descriptive named constants such as NONE and FIXED_SINGLE.

The designers of Visual Basic took every possible control property value and assigned names to them so that you can use either the names, which are usually easier to remember than actual numbers, or the values themselves. Once you get used to using named constants, you will rarely use the actual values.



Warning: Don't fret. The use of named constants will make a lot more sense when you begin building your own applications.

All the named constants are stored in a file named CONSTANT.TXT. You can add CONSTANT.TXT to your AUTOLOAD.MAK's Project file so that all the applications you eventually create automatically contain that file as well. Follow these steps to add CONSTANT.TXT to the Project window of AUTOLOAD.MAK:

  1. Select File Add File from the menu bar. Visual Basic displays a File Open dialog box.
    Visual Basic assumes that you want to add either a form (.FRM) file, a Visual Basic language (.BAS) file, or a custom control description (.VBK) file. Therefore, Visual Basic displays only those kinds of files. Instead of adding one of those files, you want to add a text file, which typically has a .TXT filename extension, as in CONSTANT.TXT. Therefore, you must override the suggested filenames in the File Name prompt.

  2. Type CONSTANT.TXT for the filename, and press Enter or click the OK command button. Immediately, Visual Basic adds CONSTANT.TXT to the project window, as shown in Figure 4.3.

  3. Save the AUTOLOAD.MAK file so that the changes you have made using File Save Project are reflected in all future projects that you create.

Figure 4.3. The CONSTANT.TXT file is part of the Project window.

Review: The AUTOLOAD.MAK file determines what all subsequent projects that you create will initially look like. If you remove the custom control files that you find in AUTOLOAD.MAK's Project window and add the CONSTANT.TXT file, all new projects that you create will initially contain CONSTANT.TXT.

Quick to the Draw!


Concept: Finally! You will now use Visual Basic to create your very own fully working Windows program. If you don't think that you know enough about Visual Basic to write programs, hang on because you will see how easy creating a program can be. Follow these steps to create your first Visual Basic application:

  1. Select File New Project to open a new application with a Project window that looks like AUTOLOAD.MAK's that you just saved. Visual Basic opens a new project and a blank Form window on which you will place controls.

  2. Double-click the label control. Remember that the label control is the uppercase A on the Toolbox window. A blank label control (with the terrible default Name property of Label1) appears in the center of the Form window.

  3. Press F4 to bring the Properties window into view.

  4. Scroll the Properties window to the Caption property. The Caption property, by default, contains the name of the label. Because the Caption property holds the label's text, you should change the text. If you highlighted the Caption property, type My First! and press Enter. As Figure 4.4 shows, the label immediately displays the new caption.

    Figure 4.4. After changing the label's caption.

  5. Click and hold the mouse cursor over the label that you just added, and drag the label towards the top of the Form window. Leave about an inch between the top edge of the label and the top edge of the window. Center the label under the title of the form. By default, the title is the name of the form, Form1. (You will change control names from their default names in the next unit.)

  6. Double-click the command button control on the Toolbox window. A command button appears in the center of the Form window.

  7. Type the following exactly as you see it: E&xit. The ampersand (&) causes the x to be underlined, as you can see when you look at the resulting command button's caption. The Caption property is the first property that changes because the last property that you changed when you worked with the label control was its Caption property.

  8. Center the command button by dragging the command button a little to the left. Once you center the command button, double-click it. Immediately, Visual Basic opens a Code window as shown in Figure 4.5.

    Figure 4.5. The Code window opens when you double-click a control.

  9. Visual Basic knows that you want to write an event procedure that executes whenever the user clicks the command button. You can tell that Visual Basic opened an event procedure for a command button keypress because the name of the procedure is Command1_Click (). (Don't worry about the parentheses right now.) An event procedure always takes the following format:
    ControlName_EventName ()
    The default name for a new command button (until you change the Name property) is Command1, and the event that triggers when the user clicks a command button is Click. Therefore, the code that handles this command button's click is Command1_Click ().

  10. The two lines that Visual Basic adds to the event procedure are called wrapper lines or wrapper code because they wrap around the code you add to the event procedure. For this event, simply press Tab and add End. The full event procedure should look like this:
    Sub Command1_Click ()
    End
    End Sub

  11. That's it. To see your handiwork, close the Code window and press F5 to run the application you just created. The application's form appears on the screen with its two controls, as shown in Figure 4.6.
    To terminate your application and return to Visual Basic, click the Exit command button. As soon as you click the command button, the event procedure that you added executes. The End statement that you added to the event procedure also executes. The sole purpose of End is to terminate the application.

Figure 4.6. Your first application works like a charm!



Other command button events: Other events are possible with command buttons. Open the Code window and look at the other event names. Click the down arrow at the right of the Code window's Proc: dropdown list. Scroll through the list. You will see that there is a DragDrop event for when the user drags the command button with the mouse and a KeyDown button for when the user presses the command button's shortcut access key, among others.
Other kinds of controls, such as the list box or label control, might have events that are identical to those of the command button control, but the other controls also have different events. The Code window's Object: dropdown list always contains a list of the application's current objects—such as the form and any controls you have added—and the Proc: dropdown combo list contains a list of events for each of the controls that you highlight in the Object: list.


If you want, you can save this application. However, the disk that comes with this book contains the full application; it is called MYFIRST.MAK. Therefore, if you save your work, save it under a different filename.

When you save your applications, Visual Basic wants you to name both the form and the entire project. Usually, especially for the one-form applications that you will write in this book, you name the form the same name as the project, but both have different filename extensions. Suppose that you want to save the project under the name FIRST. To save the project, follow these steps:

  1. Select File Save Project. Visual Basic opens the Save As dialog box for the form. Type FIRST and press Enter. Visual Basic adds the .FRM extension.

  2. Visual Basic now displays the Save Project As dialog box. Type FIRST and press Enter to save the project. Visual Basic adds the .MAK extension.

  3. You can now exit Visual Basic and take a deserved rest.

Review: With a few keystrokes and mouse clicks, you can create a fully working Visual Basic application. If you rerun the MYFIRST.MAK application, you will see that you can maximize, minimize, and resize the application's window. Visual Basic automatically adds a control button in the upper-left hand corner of the window with which you can control the application from the Windows system level.

Homework



General Knowledge


  1. What is an event?

  2. Why are GUI-based programming environments such as Windows event-driven?

  3. True or false: Windows passes all events that happen in your program to Visual Basic.

  4. What are properties?

  5. What must you write to handle events?

  6. Name two properties for any control that you can think of after reading this unit.

  7. True or false: Forms have properties.

  8. True or false: Forms are objects.

  9. Which window do you use for changing property values?

  10. What is program maintenance?

  11. What advantage does using a three-letter prefix offer?

  12. Why should you write Windows programs that look and work in a manner that is consistent with other Windows programs?

  13. What is the name of the file that describes all new projects?

  14. What is the name of the file that holds named constants?

  15. What are named constants?

  16. True or false: Visual Basic assigns well-named control names by default.

  17. How can you open a Code window for a control's primary event property?

  18. How are event procedures named?

  19. What are the first and last statements in an event procedure called?

  20. What Visual Basic command terminates a running program?

  21. What does the Code window's Object: dropdown combo list contain?

  22. How does the filename of the form differ from the name of the project?

  23. What object does frmStartUp describe?

  24. What object does cboNameChoice96 describe?

  25. What object does cmdPrintIt describe?


Find the Bug


  1. Victor the Visual Basic programmer just got a new CD-ROM with tons of great fonts. Victor decides to use a different font for every word on his form. Can you help show Victor the light?

  2. Describe what is wrong with each of these Name properties:

    1. End

    2. 96JanSalesList

    3. cmdStar$

    4. July-List


Extra Credit


Create a new project that contains two control buttons. Add a Beep statement to the wrapper of the first button’s Click event procedure, and change the Caption property to Ring a Bell. (Beep is a command that rings the PC's bell.) Change the second command button's Caption property to Exit, and type End for the Click event procedure. Run the program and test your results.

Previous Page Page Top TOC Next Page