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.
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 fingertipssteering 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
eventnamely, 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.
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 canand cannotdo 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 consistencyit is used for most Windows programsyou, 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.
Concept: Although you will learn all about
control properties throughout this book, one control property is worth learning about early onthe 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 conventionsfor 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.
The
following are valid names:
cmdExit
ListBoxJan
Nov95Combo
TitleScreen
and these are not:
Select
723
cmdExit&Leave
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 notationmixing 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.
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:
frmOpening
lstSelections
chkBooksInPrint
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 assignsyou 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.
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 wont 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 wont 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:
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 1a fixed single-line
borderand 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:
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.
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:
Figure 4.5. The Code window opens when you double-click a control.
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 objectssuch as the form and any controls you have addedand 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:
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.
Create a new project that contains two control buttons. Add a Beep statement to the wrapper of the first buttons 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.