


Chapter 2
Analyzing Visual
Basic Programs
This hour's lesson pinpoints the concepts you learned in the previous hour. You
will analyze a sample program in depth to learn more about how a Visual Basic application's
components work together to form one executable program. Although this lesson might
raise a few more questions than it answers, that's good! You need this overall walkthrough
before you get your hands dirty with Visual Basic in Hour 3, "Controls and Properties."
Don't worry, this lesson is not all theory and description! The final part of
this lesson walks you through the building of a complete Visual Basic application.
A little help from the VB Application Wizard will go a long way.
The highlights of this hour include
- What events are
- How to respond to events
- When to use event procedures
- How to name event procedures
- When to use the VB Application Wizard
Event-Driven Programs
Lots can happen when a Windows program executes. For example, consider Figure
2.1's Microsoft Excel screen. What can happen next? What exactly will the user at
the keyboard do? The user might click a toolbar button. The user might select a menu
option. The user might press F1 to get help. The user might scroll the window. The
user might enter additional numbers or formulas. The user might edit existing worksheet
cells. The user might switch to another program. The user might....
Figure
2.1. A Windows program never knows what
will happen next.
In the old days of programming, less than a decade ago, before windowed environments
became so popular, the program dictated what the user could next do. The program
might ask the user a question, and the user could answer the question and nothing
else until the question was answered. The program might display a menu of options.
Although the user had the choice of options, the user only had the choice of a menu
selection. If the user wanted to move to another part of the program, he could not
unless such a move was part of the currently displayed menu.
The multitasking, multiuser windowed environments changed everything. Today's
Windows program has no idea what might happen next. The program must offer a plethora
of choices that range from menu options to various controls and data-entry locations,
and the program just has to wait and see what happens.
New Term: An event is something that
happens, usually but not always due to the user at the keyboard, during a program's
operation.
When the programs lost control, users gained. Users can now perform any one of
many tasks. The problem for the programmer is responding to users' actions when so
many actions are possible. Fortunately, Microsoft designed Windows to be elegant
not only for the user but for the programmer as well. When virtually anything happens
in the Windows environment, Windows generates an event. An event might be a keypress,
an internal clock tick, a menu selection, a mouse click, a mouse movement, a task
switch, or one of many hundreds of other possible events.
Your program does not have to wait around for the user to do something specific.
In text-based programming days, you would write one big program that guided the user
through the execution of the code step-by-step. The program would take the user to
a menu, ask the user questions, and offer only a limited set of choices. In many
ways, a Visual Basic program is nothing more than a collection of small routines.
These routines, called event procedures, handle individual events. If and only if
an event occurs for which you've written an event procedure does that event procedure
execute. You don't have to do anything special to execute the event procedure--just
write the code. In other words, your program responds to events by supplying a matching
event procedure and your program ignores events if you've not written an event procedure.
Control Events
Every control you place on a form supports one or more events. For example, if
you place a text box in the center of the Form window and run the program, you can
click the text box, enter text in the text box, double-click the text box, and ignore
the text box. The Text Box control happens to support events that can recognize when
you've done anything to the control.
If you've written an event procedure for that text box's event, your code's instructions
will execute automatically as soon as the event occurs. Therefore, if you've written
code to blank out the text box as soon as the user clicks the text box and you've
written another event procedure for the double-click event that fills the text box
with X's when the user double-clicks the text box, the text box fills with blanks
or X's when you run the program and click or double-click the text box.
NOTE: You'll see plenty
of examples in this and subsequent lessons that demonstrate the nature of event procedures.
Analyzing a Sample
Application
Perhaps the best way to begin learning about application creation with Visual
Basic is to analyze one of the sample applications that comes with Visual Basic.
You will gain some practice working within the development environment and you will
master the various windows quickly.
To begin, perform these steps:
- 1. Start Visual Basic. If the New Project dialog box appears, close the
dialog box because you will open a project without the dialog box's help in the next
step.
2. Select File | Open Project (a toolbar button does this, too) to display a
list of directory folders from which to choose. Double-click the folder named samples
to display its contents. You will see various folders with sample projects in them.
3. Double-click the folder named PGuide to display additional sample
folders. Double-click the folder named Vcr to display the only project file
in the folder, named Vcr.vbp (the extension might not appear if you've turned
off the display of filename extensions in Windows Explorer).
Although only a single filename appears in the Open Project dialog box, several
files actually reside in the Vcr folder. Visual Basic knows, however, that
when you select File | Open Project, you want to open a project and not another kind
of file, so Visual Basic displays only project files in the dialog box. All project
files end with the .VBP filename extension to distinguish them from form
files that end with the .FRM extension and module files that end with .BAS
(other Visual Basic file types exist, but we won't cover them here).
The advantage that projects present to the Visual Basic programmer is that a project
is a guidekeeping record of the entire collection of files that comprise an application.
When you write even a simple Visual Basic application, Visual Basic creates a project
for that application so that, as the application's functionality grows, the project
can track all the files related to that project. No matter how many files go with
a project, when you open the project, Visual Basic puts the project's files at your
fingertips in the Project window.
Double-click the Vcr.vbp project file now. Double-click the form named
frmVCR in the Project Explorer window if you don't see VCR in the
Form window. Your development environment changes dramatically to hold the project,
as shown in Figure 2.2.
As you might guess from the name of the project and from the window in front of
you, this application simulates a television playing a videotape. Click any plus
signs you see in the Project window to expand the list to look like Figure 2.3. You
now know that this application is a collection of five files: two forms, a module
file, and two class files. Actually, a sixth file goes with the project: the Vcr.vbp
project file itself, which Visual Basic keeps track of and updates as needed.
Figure
2.2. The Vcr.vbp project.
Figure
2.3. The Project file lists the contents
and filenames.
The Project window describes two important aspects of a VB project: the external
disk drive filenames for each project file and the internal names used inside the
project. For example, the current form open in the Form window is named frmVCR.
You know this because VB's title bar names the file currently showing at the top
of your screen and also shows that the file is a form and not another kind of file.
To every area of your project, the form is called frmVCR. This form got
its name because the program writer named the form frmVCR. As you'll see
throughout this tutorial, programmers often precede items they name with a three-letter
abbreviation for the object being named. Thereafter, when you look through a list
of object names, you'll know just from the names what the names represent.
The form is not stored on the disk drive under the name frmVCR, however.
As the Project window's parentheses show, the form named frmVCR is called
vcr.frm on the disk. Rarely will the actual filename match that of the internal
name used in the project. In a way, the three-letter abbreviated prefix works a lot
like the three-letter filename extension in that the prefix describes the type of
object.
The naming rules for internal Visual Basic names differ from those of files. Therefore,
you will need to give each object you create in the Project window both a filename
and an internal VB name. If you don't supply a name, Visual Basic supplies one for
you, but Visual Basic is not good at assigning names to objects. VB would be happy
calling every command button on your form Command1, Command2, and
so on. When you name command buttons, however, you'll make up names that better match
their meaning, such as cmdOK and cmdExit.
Naming Objects
As you create applications and add to them objects such as forms and modules,
you will have to come up with lots of names so that both you and Visual Basic can
distinguish one object from another. Unlike filenames, a name of a Visual Basic object
must begin with an alphabetic character and can contain letters and numbers, but
it cannot contain periods or certain other special characters. You can mix uppercase
and lowercase as much as you wish. The illegal period is the primary reason why internal
object names differ from filenames.
Generally, as stated previously, programmers prefix a name with letters representing
the kind of object they are naming. The prefix is often stated in lowercase letters
and the rest of the name often appears as a combination of uppercase and lowercase
letters, with the uppercase letters helping to separate parts of the name. clsTape
is the name of one of the class files (this guide does not dive too deeply into classes,
although you'll learn some about them as you go along), and cls indicates
that the file is a class file and Tape is the rest of the name to help describe
the contents of that file. (Notice that the programmer did not precede the VCRModule
file with mdl or mod and that doing so would better describe the
file's module type.)
Double-click the form named frmSetTime. The form named frmSetTime
appears in your Form window, replacing the previous form, as shown in Figure 2.4.
Figure
2.4. A different form now appears in the
Form window.
Display frmVCR form once again. Look at the Form Layout window to determine
where the form will appear on your screen when you run the application. The next
section explains how to run the application.
Running Applications
You learned in Hour 1, "Visual Basic at Work," that you can execute
a Visual Basic application by running the application or by first compiling the application
and then running the executable compiled program. For the majority of your VB training,
you'll run applications from within the Visual Basic development environment without
taking the time to compile the application first. Usually, compilation is the last
step a programmer makes before distributing the application to other users.
Generally, and for all of this tutorial, you'll run your applications from within
the Visual Basic development environment. When you run within the development environment,
you gain all kinds of advantages that your users will not need. You can stop the
program in midstream and analyze values (using the debugging tools available in the
development environment), you can start and stop your program at any point, you gain
access to the source code faster each time you stop the program, and the program's
startup is faster than having to wait on the compiler.
TIP: When you are ready
to distribute your application, select File | Make to start the compilation process.
Although several ways exist to run the program, the easiest is to press F5, the
accelerator key for the Run | Start menu option. (A Start toolbar button also gives
you quick access to the application's startup.)
NOTE: Right before
starting the application, take a quick look at the Form Layout window. Notice where
the primary frmVCR appears relative to the rest of the screen. When you
start the application, the Form Layout window will prove to be correct; the Form
window appears right where the Form Layout window showed.
Press F5 now to see the running application. The application contains VCR-like
buttons at the bottom of the form. Click the Play button (>) to watch Figure 2.5's
butterfly fly across the television screen. When you change channels, the television
screen color changes, but the flying butterfly is the only program you can see. Click
Set to see the second Form window and click Eject to close the program.
Figure
2.5. Running the application.
Now that you've seen the Form Layout window in action, consider closing the window.
You'll rarely use it and it gets in the way most of the time. You can control the
exact twip location where a form first appears through code, and the Form Layout
window is nice just for testing purposes most of the time.
When you close the Form Layout window, you'll have a better view of the form.
Notice all the buttons, windows, text, lights, stopwatch symbols, and butterfly graphics
you see on the form. All these objects are controls the programmer got from the toolbox.
WARNING: Don't confuse
the Toolbox window with the toolbar. The toolbar is the row of buttons that mimics
certain menu options and appears directly beneath the menu bar. The Toolbox window
holds your tools, a collection of controls that you place on forms.
Click one of the buttons once to see that button's properties appear in the Properties
window. Figure 2.6 shows the Properties window for the record button labeled Rec.
Each button supports a unique set of properties to differentiate the button from
surrounding buttons. For example, the record button is named cmdRec (the
cmd prefix stands for command button) and has a Caption property
value of Rec but the Stop button is named cmdStop and has a Caption
property of Stop. Although many of the two buttons' properties are identical,
the differences set them apart, as you can see when you scroll through the Properties
window.
Figure
2.6. The Rec command button's Properties
window.
Wheres the Code?
This lesson began by describing code and event procedures in detail, and yet not
a word has been mentioned about that in several pages. The code is there, as you
can see from the Project Explorer window. Actually (ignoring the class files for
now), this application contains three sets of code!
Controls cannot have the same name if you place them on the same form, but two
forms might contain controls with the same name. A control name goes with its parent
form. For example, an application might contain an About dialog box and a form that
displays account information. Both forms can have a command button named cmdExit
that closes the form's window. Each form contains its own code, called the form module,
that manages and responds to the controls on that form. You won't always put code
in a form's form module, but you very frequently will.
The Project window's Modules entry also is a file with code in it. A module file
that lies outside a form module is often called a standard module. You'll place event
procedures for forms in the forms' form modules, and you'll place common routines
that work on all the forms in a standard module file that lies outside the form module
but still in the project.
TIP: As you write more
code, you will write routines that you want to use again, such as special calculations
that are unique to your business. By storing these general-purpose routines inside
modules instead of embedding them in form modules that go with specific applications,
you can copy and load the standard module into multiple applications so that you
don't have to type the general-purpose code more than once. Therefore, once you've
written a useful procedure that calculates or processes data outside the form's boundaries,
you can reuse that code and insert the code into other projects as long as you keep
the routines in a standard module file.
New Term: You enter, edit, and view
the language of VB in the Code window.
Visual Basic always presents you with code in the window. A Code window acts a
lot like a simple text editor or word processor. You can insert, delete, copy, cut,
and paste text. Despite the graphical nature of applications and the controls, the
code you write to tie things together is still in text.
Take a brief look at the application's single module's Code window by double-clicking
the Project window's VCRModule entry. Visual Basic opens the module's Code
window, as shown in Figure 2.7.
Figure
2.7. The module's Code window.
Code appears in the Code window in various colors to indicate the purpose of the
code. As you learn the Visual Basic language, you will better understand why some
code is green and some black. Scroll down through the Code window. Don't worry about
understanding much or anything about the Code window at this time. As you can see,
much of the Code window contains English words, but the structure might seem completely
odd if you've never programmed before. By the time you finish this 24-hour tutorial,
you will understand the entire program and be able to speak the Code window's language
fluently!
Close the module's Code window for now. To close the window, you can click the
window's (not VB's!) close button or double-click another object in the Project window
such as the primary form named frmVCR. However you close the window, make
sure that you see the VCR form before you start the next section.
Event Procedures
Visual Basic makes it easy to locate event procedure code for controls on forms.
Double-click any control to see one of its event procedures. For example, if you
double-click the command button labeled Up, Visual Basic opens the Code
window and places the text cursor in the set of lines that Listing 2.1 shows.
Listing 2.1. The
Up command buttons Click event procedure
Private Sub cmdUp_Click()
` if in range, set the channel number
If vntChannel < 13 Then
vntChannel = vntChannel + 1
Else
vntChannel = 2
End If
` assign the channel variable to the display
lblChannel.Caption = vntChannel
End Sub
New Term:Wrapper lines are the first and
last lines of a procedure.
Don't sweat the details, but get familiar with the overall event procedure. Most
event procedures begin with the statement Private Sub and end with End
Sub. The Private-End block (a block is a section of code that goes
together as a single unit) illustrates the first and last lines of the event procedure.
The lines between these wrapper lines comprise the body of the event procedure.
All controls have unique names, as you saw earlier. All event procedures also
have unique names. An event procedure name always takes this form:
controlName_eventName ()
WARNING: The parentheses
are not actually part of the name. Some procedures require values inside the parentheses
while others do not. Even if an event procedure requires nothing inside the parentheses,
the parentheses are still required.
The event procedure always consists of the control name, an underscore, and the
procedure's event name. Therefore, if you want to respond to both the click and double-click
events that might be applied to the command button named cmdUp, you would
have to write an event procedure named cmdUp_Click() and one named cmdUp_DblClick().
You don't have to memorize that the double-click event is named DblClick
and that a keypress event is named KeyDown. The top of every Code window
contains a drop-down list box that contains every event possible for the control
listed in the right-hand drop-down list box. The left-hand list box holds the name
of every control on the form that this form module goes with. Again, do not get too
bogged down in details because when it is time to use these drop-down list boxes
to select events, this lesson describes the process in detail.
The naming convention for the event procedure is not up to you, but up to Visual
Basic. In other words, the Click event procedure for a command button named
cmdTest will always have to be cmdTest_Click(). The two-part name
makes the event procedure extremely specific; from the name both you and Visual Basic
know that the code executes only if the user clicks the command button named cmdTest.
Properties and Event
Procedures
This might be a good time to review properties. When the programmer (you!) places
controls on a form, the programmer generally sets many of the control's property
values at that time in the Properties window. A programmer might then write the event
procedure code for the control or the programmer might place additional controls
on the form and write event procedures later.
Many of the properties in the Properties window show up immediately, during design
time, as you assign the properties. In other words, if you place a command button
on a form and immediately click the Properties window's Caption property
and type Click Here, the command button instantly reads Click Here in the
Form window.
The event procedure code, however, does not do anything until runtime. The instructions
you learn to place in the event procedures will not execute until the application's
user runs the program and triggers events at runtime. The Properties window often
reacts at design time, whereas the Code window often reacts at runtime.
Generating an Application
from Scratch
Enough already! How about a little fun? You can create your very first Visual
Basic application without knowing any more than you know now about Visual Basic.
The secret is Visual Basic's VB Application Wizard, a wizard that generates an application
for you based on your responses to a series of dialog boxes.
New Term: A skeleton program is a program
shell that you must fill in with specific code.
WARNING: The application
that the VB Application Wizard generates is known as a shell or skeleton. The application
will not do much. For example, how can the VB Application Wizard create a real estate
analysis application for you and know all the details and processing requirements
and calculations that you might require? The VB Application Wizard's purpose is to
build only a shell by following your guidelines. The shell is just a program structure
that executes but contains no specific functionality. The shell contains a menu,
a toolbar, and several other features, but these features are more like placeholders
for you until you get around to editing the generated application to make the application
perform a specific task that you need done.
Despite the ease with which you can generate an application with the VB Application
Wizard, this guide does not revisit the VB Application Wizard after this section.
You need to get well grounded in Visual Basic before you will really understand how
to add to the shell and change the shell to suit your needs. Therefore, the VB Application
Wizard arguably benefits the experienced Visual Basic programmer more than the beginning
programmer because the experienced programmer will be more able to decipher the generated
shell and add specifics to make the program operate as needed.
Perform these steps to generate your first Visual Basic application with the VB
Application Wizard:
- 1. Select File | New Project. Click No at the dialog box that asks if
you want to save the Vcr project because you don't want to overwrite the
sample application. (You made slight changes to the project if you moved the Form
Layout window's form around or closed windows that were open, but you should not
save those changes to the sample application.)
2. When the New Project dialog box appears, double-click VB Application Wizard
to start the wizard.
3. Read through the wizard's dialog boxes and click Next when you're ready to
move to the next dialog box. Keep all the default values along the way. As you'll
see on the Menus dialog box (shown in Figure 2.8), the wizard gives you a choice
of menu items you want to see on the generated application's menu bar. Although menus
are relatively simple to place in a Visual Basic application, the wizard makes placing
menus much simpler because you only need to check the boxes next to the items you
want on the final application's menu bar.
4. As you click through the wizard, look for the dialog box that describes the
application's Internet connectivity. The generated application, despite being a shell,
can access the Web directly. You can send your application's users to a Web page
or let them view Web pages from inside your own application! The real magic is that
the wizard handles all the details for you if you want the options! For now, don't
select Internet access but keep moving through the dialog boxes by clicking Next.
Figure
2.8. Selecting the menu items you want
to place in the final application.
5. The wizard gives you a chance to interface with a database, such as Microsoft
Access, before taking you to the final dialog box, where you click Finish to watch
Visual Basic's wizard perform its wizardry. Right before your eyes, the wizard will
put the application together, add the forms, and build the menus.
6. Click the closing dialog box and close the final instructions. The wizard
leaves your development environment fairly clean, but you know that you can double-click
any object in the Project window to see forms and code modules. For now, simply run
the program to see Figure 2.9's screen.
Figure
2.9. The wizard generated a working, albeit
plain, application.
The generated program looks somewhat like a word processor because of the large editing
area in the center of the screen. Try the menus and click the toolbar buttons. Things
look good. You will find that the application does not respond to your keystrokes
as you might expect, however. If you select and attempt to cut, copy, or paste (despite
the toolbar and menu items that represent those tasks), either nothing happens or
a small dialog box appears, telling you what you requested (such as the paste command)
but doing nothing about the request.
You must remember that it's not the wizard's job to generate a fully working application
that performs specific tasks. The wizard's job is to construct a general application
to which you can later add the specifics. As you learn more about Visual Basic, you
will better appreciate how much time and effort the VB Application Wizard saves you
because the simple task of adding a standard menu and toolbar buttons can take an
afternoon. The generated application is a great starting point for your own applications
once you and Visual Basic become better acquainted.
Summary
You've just created your first application! Actually, you got a little help from
your friend the VB Application Wizard, but that's okay. You are now beginning to
understand how a Visual Basic application's components fit together. The events that
the user triggers are often related directly to your application's forms or controls,
and you now know where to place the code that handles the important events.
The next hour takes a small step backward and lets you begin to create an application
from scratch without the help of the wizard. You will better learn how the toolbox
and Properties window interact and support each other's activities.
Q&A
- Q How do I know which events to respond to when so many events can happen
at any time?
A Your application's requirements determine the events you respond to in the
application, nothing else. For example, if your application has no need to respond
to a mouse click over a label you've placed on the form, don't write an event procedure
for that label's Click event. If the user clicks over the label, Windows
will send a message signaling the event to your program, but your program simply
lets the event pass through and never responds to the event.
Q Why should I not compile my application before I run the application if compiling
the application makes it more efficient?
A When you compile an application, Visual Basic translates your source code project
into an executable program. The executable program often takes less disk space than
all the source files, and the executable program is easier to distribute. Nevertheless,
when you develop and test an application, you don't want to compile the application
every time you run it to test the application and see the results. As a matter of
fact, don't compile your application until you have completely finished the application
and are about to distribute it to others. The compiled application is safe from modifications
because a compiled program is virtually impossible to change without ruining the
application's executable file. In addition, the compiled file will be faster than
the project that you run from inside the development environment. Nevertheless, during
development, you don't care about speed, but you do care about bugs. During debugging
test runs, you want your project to execute as soon as you request without taking
the extra time necessary to compile each time.
Q What is the difference between a form module and a standard module?
A A form module always goes with its form. The form holds controls, remember,
and each of those controls can trigger and respond to events. The event procedure
code that you write for the form's controls must reside in that form's form module.
General-purpose routines, such as common calculations that several applications must
share, should go in a standard module with the .BAS filename extension.
By the way, not only can other applications utilize standard module files, but you
can add the same form and form module to multiple applications as well. The application's
Project window will take care of the guidekeeping details.
Workshop
The quiz questions and exercises are provided for your further understanding.
See Appendix C, "Answers," for answers.
Quiz
- 1. How do windowed programs differ from programs running in text-based
environments?
2. What are events?
3. Why are project component filenames not usually the same as their internal
VB names?
4. What is usually the last step a VB programmer takes before distributing an
application to users?
5. How does Visual Basic know which procedure to execute for a particular control's
event?
6. True or false: All controls support one and only one event.
7. Which usually respond at design time: control property changes or event procedures?
Exercises
- 1. Scroll through the Vcr.vbp project's form modules again, looking
at the various event procedures coded there. Surely you'll be able to spot exactly
which events are handled and which are not. An event procedure whose first name half
is Form is an event procedure for the form itself. For example, you can
respond to the user's mouse click over the form differently from a mouse click over
a command button. Look for the events associated with the various command buttons
on the form. Most often, a command button's event procedure is a ...Click()
or ...DblClick() event procedure because most users either click or double-click
command buttons and the click and double-click events are the ones you often need
to respond to.
2. Run the VB Application Wizard once again and, this time, test other features
by including more objects (such as the Internet and database access if your disk
drive contains a database file somewhere that you can locate when the wizard asks
for the location) and selecting different options. Run the generated shell to see
how differently the wizard's generated shell applications can act.


