Sams Teach Yourself Visual Basic 6 in 21 Days, Professional Reference Edition

Sams Teach Yourself Visual Basic 6 in 21 Days, Professional Reference Edition

Paperback(PROFESSION)

$41.76 $49.99 Save 16% Current price is $41.76, Original price is $49.99. You Save 16%.

Overview

Visual Basic programming techniques are presented in a logical and easy-to-follow sequence that helps you really understand the principles involved in developing programs. The reader begins with learning the basics to write a first program and then moves on to adding voice, music, sound, and graphics. After reading this book, the reader will be able to write their own DLLs, create ActiveX controls, use object linking and embedding (OLE) and write Visual Basic programs that support multiple document interface, and much more. Various topics covered are: Properties, Controls, and Objects Graphics Controls & Methods Interfacing with Windows Arrays, OLE, and other topics Data Control and SQL Multiple Document Interface ActiveX Sound Programming and DirectSound Building ActiveX Controls and all the latest features of Visual Basic
  • Combines the proven Sams' Teach Yourself format with the most popular programming language on the market.
  • Enables the reader to create and use ActiveX controls.
  • All of the previous editions of Sams' Teach Yourself Visual Basic in 21 Days have been bestsellers.With its ever-expanding installed base, Visual Basic continues to be the most popular programming language on the market. Combines the best learning tools with the most popular programming language.

Product Details

ISBN-13: 9780672315428
Publisher: Sams
Publication date: 05/17/1999
Series: Sams Teach Yourself Series
Edition description: PROFESSION
Pages: 1088
Product dimensions: 7.70(w) x 9.41(h) x 2.61(d)

Read an Excerpt







Sams TY VB 6 in 21 Days - CH 3 - Managing Controls


[Figures are not included in this sample chapter]

Sams Teach Yourself Visual Basic 6 in 21 Days


- 3 -


Managing Controls


Now that you've created two applications, one with the Application wizard and
one from scratch without the help of the wizard, it's time to begin studying how
Visual Basic works. The previous two days' worth of hands-on sessions showed you
how easy it is to create programs and helped give you a feel for the Visual Basic
environment. Starting today, you'll begin to understand how the components of a Visual
Basic program go together, especially how the controls and properties work together.


Today, you learn the following:


  • Common control properties
  • Why controls come with so many properties
  • About the more common tools on the Toolbox window
  • How accelerator keys help speed data entry
  • How focus helps users select controls
  • How event procedures work

Studying Controls


The toolbox holds the collection of controls that you use in your applications.
The toolbox does not hold a limited number of each tool; in other words, you can
double-click the Label control as many times as you like as you create your forms;
Visual Basic sends a new label to the target form each time.


The collection of controls (also called tools) on the toolbox varies depending
on your application's requirements. For much of this 21-day tutorial, the toolbox
will hold the same set of tools you saw in yesterday's lesson. These tools are the
standard controls loaded when you create a new application.





CAUTION: A control is not available to your program until that control appears
in the toolbox. Therefore, you cannot, for example, add an Internet browsing control
to your form until you add the Internet browsing control to your toolbox. If you
use the Application Wizard, the wizard will add controls to the toolbox when needed
to generate your project.






NOTE: When a lesson in this book requires a control not found on the standard
toolbox, the lesson will explain how you can add that control to your toolbox.



As Figure 3.1 shows, your toolbox can get quite complicated when it fills up with
too many controls. Such a large toolbox can take away from your other windows' space.
You can drag the Toolbox window's title bar to another location if you want to use
the left edge of your screen to view your form. In addition, you can resize the Toolbox
window for more or less room.


FIGURE 3.1. The Toolbox window should be a manageable size.






DON'T make the Toolbox so small that tools get hidden from view. No scrollbars
appear if you size the Toolbox window so small that some controls are no longer visible.
To use the controls that are outside the window's boundaries in this case, you have
to expand the Toolbox window until the hidden tools appear once again.



NEW TERM: Visual Basic purists apply more strict names to the sets of controls
available. The controls that first appear in the Toolbox window are called the intrinsic
controls
. The ActiveX controls, with the .OCX extension, are external controls
you can add to the Toolbox window. Insertable controls are controls made from
external applications, such as Microsoft Excel.


Many of the controls require similar properties. Table 3.1 lists some common properties
that most controls support. You can probably see why so many of Table 3.1's properties
exist for multiple controls. All controls have a screen location (indicated by the
Left and Top properties) and a size (indicated by the Width
and Height properties), and most have foreground and background colors as
well as font properties, if the controls display text.

TABLE 3.1. COMMON PROPERTIES FOR SEVERAL VISUAL BASIC CONTROLS.




































































Property Description
Alignment Determines whether text on the control, such as a label or command button, is left-justified,
centered, or right-justified on the control.
BackColor Specifies the color of the control's background, which you select from a palette
of colors when you open the property's drop-down list box of colors.
BorderStyle Determines whether the control has a border around it.
Caption Lists the text displayed on the control.
Enabled Set by a drop-down list box, this property is either True if you want the
control to respond to the user or False if you want the control not to respond
to the user. This property is useful for turning on and off controls when they are
and are not available during a program's execution.
Font Displays a Font dialog box from which you can set various font properties, such as
size and style, for a control's text.
ForeColor Specifies the color of the control's foreground, which you select from a palette
of colors when you open the property's drop-down list box of colors.
Height Specifies the number of twips high the control is.
Left Indicates the starting twip from the left edge of the form where the control appears.
For a form, the Left property specifies the number of twips from the left
edge of the screen.
MousePointer Determines the shape of the mouse cursor when the user moves the mouse over the control
at runtime.
Name Specifies the name of the control. As you saw in yesterday's lesson, the Properties
window displays the Name property in parentheses so that it appears first
in the list of properties.
ToolTipText Holds the text that appears when the user rests the mouse cursor over the control
at runtime (similar to ScreenTips).
Top Is the starting twip from the top edge of the form where the control appears. For
a form, the Top property describes the number of twips from the top edge
of the screen.
Visible Set by a drop-down list box, this property is True if you want the control
to be visible on the form or False if you want the control to be hidden
from view.
Width Specifies the number of twips wide that the control is.

Remember that all controls have all their property values set before you ever change
a value. As soon as you place a control, Visual Basic uses a set of predetermined
property values (the most common values) for the controls. In addition, Visual Basic
assigns default names and captions to the controls, although you'll surely want to
change these properties. Many of the default values work well in many cases. You
won't change all of a control's property values from its default set.


You already know that you can set the properties for a control when you write
the application, but you can also set and change property values with Visual Basic
code during the application's execution. For example, the Enabled property
is often changed during the execution of a program if a particular control is temporarily
unavailable to the user. You may, for example, disable a command button that produces
a report until the user has specified the contents of the report.





CAUTION: Not all properties for all controls appear in the Properties window.
Properties that you can set only with Visual Basic code do not appear in the Properties
window.






TIP: Some control properties, such as the Alignment property values,
may look strange because their drop-down list boxes display numbers to the left of
their values. For example, the Alignment property can take on one of these
three values: 0-Left Justify, 1-Right Justify, and 2-Center.
You can use your mouse to select these values from the list without worrying about
the numbers in them, but you can also, after opening the drop-down list box for a
property, type the number that corresponds to the value you want to quickly set that
value. The numbers also come in handy when you assign property values to controls
with Visual Basic code. You can assign the numeric value instead of having to type
the entire value, such as 0-Left Justify. The numbers provide
shortcuts when you write code, as you'll see in future lessons.



The following sections describe the most useful standard toolbox controls. You'll
learn about several important properties associated with those controls. Today, you
will not learn about all the toolbox's controls, just those that you'll work with
over the first few days of Visual Basic programming.


You don't need an in-depth reference on all the properties for all the controls
because some of the properties are rarely used. Most Visual Basic programmers don't
even know all of the properties available for a control. Generally, if you need to
make a control appear a certain way, a property probably exists to accomplish that.
By taking a brief tour of the controls and their properties in the following sections,
you'll better understand the purpose for the controls, and you'll have a better idea
of which properties are available.





TIP: Some programmers prefer to view properties in the Property window grouped
by category. To group properties this way, click the Properties window's Categorized
tab, as Figure 3.2 shows.




FIGURE 3.2. You can categorize properties to more quickly locate properties
you need.




The Form's Properties


Many form properties correspond with other control properties that you learned
about in Table 3.1. The form, however, is unique in that it does not reside on a
form, but appears on the user's window. That is why the form's Left, Top,
Width, and Height properties all correspond to the edge of the
screen and not to a Form window.


These form properties are important as well:


  • BorderStyle. This property determines how the Form window responds
    to the user's efforts to resize it. Some values you may need are 0-None,
    which offers a form without any edge or title bar, 1-Fixed Single, which
    offers a nonsizable window (the user can close the window but not resize, minimize,
    or maximize the window), and 2-Sizable (the default), which offers a regular
    sizable window with maximize and minimize buttons.



  • ControlBox. This property's value of True or False
    determines whether the form's Control menu appears.

NEW TERM: A Control menu is the menu that appears when you click
a window's icon in the upper-left corner of the window. The Control menu enables
you to move, size, minimize, maximize, and close a window.


  • Icon. This property specifies an icon filename for the Windows
    taskbar icon that appears when the user minimizes the form.



  • MaxButton. This property determines whether the form contains
    an active Maximize window button.



  • MinButton. This property determines whether the form contains
    an active Minimize window button. (If you set both the MaxButton and MinButton
    properties to False, neither appears on the form.)



  • Movable. This property determines if the user can move the form
    or if the form is to remain in its displayed location.



  • ShowInTaskbar. This property's True or False
    value determines whether the open form appears on the user's Windows taskbar.



  • StartUpPosition. This property provides a quick way to specify
    the starting position of the form on the screen. One of the most useful values is
    2-CenterScreen that centers the form on the user's screen when the form
    first appears.



  • WindowState. This property determines the size (normal, maximized,
    or minimized) of the form (useful for starting a minimized form).

The Pointer Tool


The pointer tool is the only toolbox item that is not a control. About
the only use for the pointer tool is to eliminate the crosshair mouse cursor that
appears when you select any of the other controls in the Toolbox window.

The Label Control


The label control displays text. Although your user cannot alter the text that
appears on a label, you can, at runtime, change the label's text through code. (See
Day 5's lesson for details.) Programmers often use labels for titles, prompts, and
descriptions. For example, when you want the user to enter a value into another control,
such as a text box, you place a label next to that data-entry location on the form
describing the value you want the user to enter. Without the label, the users would
not know what you needed them to enter.


Two properties, AutoSize and WordWrap, affect the way you display
text on a label. If you set AutoSize to a True value, the label
automatically expands horizontally across the form to display all the text you've
assigned to the Caption property. If you set WordWrap to True,
Visual Basic keeps the label's width but expands the label vertically to display
as many lines as needed to show the full caption. Figure 3.3 shows three versions
of a label with the same Caption property but with a different combination
of AutoSize and WordWrap properties, so you can study the effect
of the two properties.





CAUTION: Surprisingly, for WordWrap to work, you must also set AutoSize
to True. Visual Basic needs to be able to expand the label at least partially
horizontally if a single word in the caption is larger than the label's width.




FIGURE 3.3. The AutoSize and WordWrap properties
affect the way a label displays its caption.




The Text Box Control


Use a text box control when you want the user to type something, such as an answer
to a prompt, when you want to collect values, such as name and address information.
Often, a default value is helpful for your users, and your Visual Basic program can
supply an initial value. For example, if you are asking the user to enter a date,
you might place today's date in the text box so that the user can accept the date
without having to enter it.


Text boxes don't make for good yes/no, true/false answers. In other words, if
you must ask your user to select between two values or answer a yes or no question,
other controls--such as an option button or list box control that you'll learn about
on Days 5 and 6--are better to use.





DO use a Label control to prompt the user for a value before you offer a text
box control. In a name and address form, for example, you might place a Label control
before the name TextBox control that reads Enter your first name:. Your
users then will know what information you expect them to type in the text box.



NEW TERM: Programmers must distinguish between designtime and runtime.
Designtime is the time when you write and maintain an application. Runtime is when
you or a user runs an application. When you place a value in a text box's Text
property at design-time, you are placing the default value that the user will see
at runtime. At runtime, the user then can change the text box's value to a different
value by typing over or editing your default value.


When placing text boxes on forms, you'll find the following text box properties
useful:


  • Alignment. This property determines how the text aligns inside
    a text box whose MultiLine property is set to True. The Alignment
    property has no meaning for single-line text boxes.



  • Locked. This property determines whether the user can enter a
    value or change the default value of the text box. If True, the user cannot
    change the text box value until the program, at runtime, assigns a False
    value to this property.



  • MaxLength. This property specifies the maximum number of characters
    that the text box will accept. A value of 0 indicates that the user can
    enter a value of any length.



  • MultiLine. If True, the property specifies that the
    text box can hold more than a single line of text. A vertical scrollbar will appear
    if the user enters more text than will fit on a single line, unless you've disallowed
    scrollbars with the ScrollBars property. The Alignment property,
    whose default value is 0-Left Justify, determines how the multiple lines
    of text align.



  • PasswordChar. This property designates a character, such as an
    asterisk, that will appear in place of the characters the user types into the text
    box. In other words, if the user is entering a secret code, only asterisks will appear
    on the screen as the user types the code instead of the code's value so that nobody
    looking over the user's shoulder can read the code. Although the asterisks appear,
    the text box receives the actual value that the user types.



  • ScrollBars. This property determines if and how many scrollbars
    will appear on the text box. A value of 0-None keeps scrollbars from appearing.
    1-Horizontal allows only horizontal scrollbars. 2-Vertical allows
    only vertical scrollbars. 3-Both allows both horizontal and vertical scrollbars.



  • Text. This property specifies the initial text (the default value)
    that appears in the text box.





CAUTION: You must set the MultiLine property to True before
vertical scrollbars can appear in a text box.



A special cursor comes into play with text boxes and forms. Your user enters and
edits text using the text cursor. Clicking a text box's text places the text
cursor at that point so that the user can add, change, or delete text from within
the text box.


NEW TERM: The text cursor, also called the caret or the insertion
point
, is a vertical bar used for entering and editing text in controls such
as text boxes.





TIP: Load and run the sample application called Controls from your MSDN's
Samples folder. Select the text box option to practice using text boxes. Figure 3.4
shows the screen that appears. You will be able to practice working with single-line
and multiline text boxes as well as with the text cursor and scrollbars. The Controls
application even shows that you can select text within a text box and copy, cut,
and paste text to and from text boxes using standard Windows operations.




FIGURE 3.4. The sample Controls application lets you work with several
styles of text boxes.



The Command Button Control


Almost every application's form contains a command button. With the click of a
command button, the user can indicate that an answer is ready, a printer has paper,
or that it's time to terminate the program. As you saw in yesterday's lesson, Visual
Basic takes care of showing that the command button is pressed when the user clicks
it.


NEW TERM: An accelerator key is a key that, when combined with the
Alt key, triggers a response. For example, menu bar options all have accelerator
keys, such as Alt+F for the File menu option. The underlined letter in a menu bar
option name or on a command button's label indicates the accelerator key for that
object.





TIP: Command buttons aren't just for mouse clicks! You can add an accelerator
key
to a command button's label so that the user can select the command button
by pressing the appropriate key combination, such as Alt+R. The Caption property
determines a command button's accelerator key. In addition to an accelerator key,
the user can select a command button by pressing Enter if the command button is the
selected control (see the section called "Control Focus" for more information)
or if the Default property is True. In some cases, you may want
the user to be able to trigger a command button by pressing the Esc key, such as
when a command button offers an exit from a program and the Cancel property
handles Esc.



The following properties are useful for command button programming:


  • Cancel. This property determines how the command button responds
    to the Esc key. If True, the user can trigger (simulate a click) the command
    button by pressing Esc. Only one command button on a form can have a Cancel
    value of True. If you set more than one command button's Cancel
    property to True, Visual Basic resets all but the last one to False.



  • Caption. This property specifies the text that appears on the
    command button. If you precede a letter with an ampersand (&), Visual Basic makes
    that letter the accelerator key. A Caption of E&xit produces
    a command button such as the one you see in Figure 3.5. The user can trigger this
    command button by clicking the button or by pressing Alt+X.


FIGURE 3.5. A control's Caption property that contains an
ampersand before a letter determines the accelerator key for that control.



  • Default. This property determines how the command button responds
    to the Enter key. If True, the user can trigger (simulate a click) the command
    button by pressing Enter unless the user moves the control focus (see the next section)
    to another control first. Only one command button on a form can have a Default
    value of True. If you set more than one command button's Default
    property to True, Visual Basic resets all but the last one to False.
    The command button with a Default value of True is always the selected
    command button when a form first appears.



  • Picture. This property specifies a graphic image that appears
    on the command button in place of a caption. The Style property must be
    set to 1-Graphical before a picture will appear.



  • Style. This property determines whether a command button displays
    a text caption (if set to 0-Standard) or a picture (if set to 1-Graphical).





DO choose different accelerator keys for your controls.

DON'T use the same accelerator key for more than one control. If two or more
controls have the same accelerator key, Visual Basic will select only the first one
in the focus order (see the next section) for the accelerator key, and your
user will not be able to select any of the other controls with that accelerator key.



The Image Control


A brief mention of the image control is in order here because you placed an image
on the application you created in yesterday's program. The image control is one of
two controls (the picture box is the other) that display graphic images. The image
properties determine the file used for the image and whether the image control resizes
to fit the file or the file resizes to fill the image control's size. You'll learn
all about the image and picture box controls in Day 14's lesson, "Introducing
VB Graphics and Multimedia."


Although many more controls exist, you'll learn about the others as you progress
through these 21 days. The next section describes how the user can use the keyboard
to trigger any control on the form.

Control Focus


Only one control on a form can have the focus at any one time. The first
control with the focus is determined by the order in which you placed the controls
on the form or, more accurately, the order determined by the TabIndex property
of each control on your form. Not every control can receive focus. Only those controls
the user can interact with can receive the focus. For example, a label control cannot
receive the focus because the user cannot interact with label controls.


NEW TERM: The focus, or control focus, is the currently selected
control. Visual Basic indicates the control with the focus by highlighting the control.


For a moment, study Figure 3.6. Notice that the center command button has the
focus because it's highlighted by a dashed box. Visual Basic typically displays the
control with the focus with just such a dashed box. In the figure, if the user pressed
Enter, the center command button would trigger because that's the command button
with the focus. The user could also press Tab or Shift+Tab to move the focus to another
control. If the user pressed Tab, the third command button would receive the focus,
so then if the user pressed Enter, the third command button would be the one to respond.


FIGURE 3.6. The highlighted control has the focus, but the user can
move the focus to a different control before pressing Enter.






TIP: Remember that if a control contains a Default value of True,
that control will be the one with the focus when the user first sees the form. Of
course, the user can always move the focus to a different control.








NOTE: Notice that the third command button's accelerator key is Alt+A,
not Alt+S. The center command button already used the Alt+S accelerator key with
a Caption property value of Click for Shrug, so the programmer
had to select a different and unique accelerator key for the third command button.








TIP: Remember that if a control contains a Default value of True,
that control will be the one with the focus when the user first sees the form. Of
course, the user can always move the focus to a different control.



All controls have a TabIndex property. As you place controls on a form,
Visual Basic automatically sets the TabIndex property to 0, 1, and so on,
placing a unique and sequential number in each control's TabIndex property.
Even controls that the user does not normally interact with, such as labels, have
TabIndex properties. The TabIndex property determines the focus
order.


You will not always place controls on a form in the correct TabIndex
order. Sometimes you'll add a control between two others. You may need to change
the TabIndex order to match the focus order you desire. For example, you
may want the focus to move down the form in columns as the user presses Tab, or you
may want the focus to move across the controls in rows as the user presses Tab. The
order you want the focus to move is determined solely by the values in the controls'
TabIndex properties.





TIP: If the next control that gets the focus--indicated by the TabIndex
property--is a label, Visual Basic sends the focus to the next control in sequence.
Knowing this, you can offer your user an accelerator key for a text box that you
could otherwise not offer. Consider the form in Figure 3.7. The First Name:
label has a TabIndex one greater than the text box that follows. No matter
which control has the focus, if the user presses Alt+F, Visual Basic sends the focus
to the label, which immediately sends the focus down the line to the text box because
labels cannot normally accept the focus. When you place text boxes with description
labels on a form, consider adding accelerator keys to the labels that identify the
text boxes so that your users will have quick access to any text box they want to
enter or change. Of course, you must make sure that each matching pair of label and
text box controls has consecutive TabIndex values.



FIGURE 3.7. The user can press Alt+F to enter the first name in the text
box.



Event Procedures


Event procedures sometimes challenge beginning Visual Basic programmers, but the
concept of an event procedure is very simple. When the user presses a command button
or enters text into a text box, something has to happen that tells the application
the user has just made a move. You saw in yesterday's lesson that Windows receives
events from all kinds of sources. Most events come directly from the user at the
keyboard and mouse running applications within Windows.


When Windows recognizes that the user triggered an event and that the event is
not a system event, such as a Windows Start button click, but an event directly needed
by an application, Windows passes that the event to the application. If you've written
an event procedure to respond to that exact event, your application will respond
to the event. If you haven't written an event procedure, the event goes unhandled.


All kinds of events can occur, such as a click, a double-click, or a keystroke.
In addition, multiple controls on your form can receive the same kinds of events.
For example, both a command button and a text box can receive a Click event,
because the user can click the mouse over either control. Therefore, you must not
only write an event procedure for a particular event, but you must also specify which
control that event belongs to.





NOTE: The concept of writing event procedures for all events you want to handle
and for each control is vital to your understanding of Visual Basic. How many click-related
event procedures must you write to handle three command buttons on your form? You
must write three event procedures, because the user can click any of the three command
buttons. If you write a Click procedure that is not tied to a specific control,
your program cannot respond differently to the command buttons. You have to write
a separate Click procedure for each command button. When Windows passes
the Click event to your program, Windows also passes the control that generated
the event. Only if you've written an event procedure for both that control and that
event will your application be able to respond to the event.



Suppose your application displays four command buttons on the form. Here's the
process that can occur:


1. When the user clicks any of the command buttons, Windows recognizes
that an event just took place.



2. Windows analyzes the event and notices that the event belongs to your application.




3. Windows passes the event and control to your application.



4. If your application has an event procedure written for the control that
received the event, the event procedure's code (the code that you wrote in the Code
window) executes.




NOTE: Code inside a control's event procedure will never execute if the control's
event never takes place. This quality makes Visual Basic a very responsive system,
because you'll write all kinds of event procedures that sit around until their exact
event occurs. Then they take over no matter what else is being done at the time.




Common Control Events


You should familiarize yourself with common events that can occur for the controls
that you know about. Both the form and its controls can receive events. Here are
some common form events that can occur during an application's execution:


  • Activate. This event occurs when a form gets the focus. If an
    application contains multiple forms, the Activate event occurs when the
    user changes to a different form by clicking on the form or by selecting the form
    from a menu.



  • Click. This event occurs when the user clicks anywhere on the
    form. If the user clicks a form that's partially hidden from view because another
    form has the focus, both a Click and an Activate event take place.






NOTE: A right-click triggers the Click event when the user right-clicks
over a form. As you learn more about programming with the mouse, you'll learn how
to determine which mouse button triggered the Click event.





  • DblClick. This event occurs when the user double-clicks the form.



  • Deactivate. This event occurs when another form gets the focus.
    Therefore, both the Activate and Deactivate events occur when the
    user selects a different form. You may choose to write event procedures for both
    events for each form, for only one event for one of the forms, or a combination thereof
    depending on the needs of your application.



  • Initialize. This event occurs when the form is first generated.



  • Load. This event occurs right as the form is loaded into active
    memory and appears on the screen.



  • Paint. This event occurs when Windows must redraw the form because
    the user uncovered part of the form from under another object, such as an icon.



  • Resize. This event occurs when the user changes the size of the
    form.



  • Unload. This event occurs when the application removes a form
    from the window using code. When an application is terminated, all loaded forms are
    first unloaded, so you must write an Unload event procedure for each form
    if you want to perform some kind of clean-up or file-saving procedure at the end
    of an application's session.

The following events are common text box events:

  • Change. This event occurs when the user changes the text.



  • Click. This event occurs when the user clicks the text box.



  • DblClick. This event occurs when the user double-clicks the text
    box.





NOTE: Some events available for most controls, such as keyboard and mouse-
control events, are handled elsewhere in this 21-day tutorial.



Most of these text box events are supported by labels as well, but the nature
of labels makes them trigger the events in a slightly different manner. For example,
although a label control supports a Change event, the user cannot change
a label directly. Visual Basic code, however, can change a label, and when that happens,
the Change event takes place.

The Image control supports the same set of events as the Label control. The Image
control is a lot like a Label control except that a graphic image appears in place
of text on an image.





NOTE: Remember that many more events exist than you are learning about today.
The events described here will be useful as you begin to probe more deeply into Visual
Basic.



The command button control also supports the same set of events listed previously
for text boxes. Keep the following in mind when programming command button events:


  • When only a single command button resides on a form, pressing the spacebar when
    the command button has the focus will trigger the command button's event procedure.



  • If a command button's Cancel property is True, pressing Esc
    triggers the Click event.



  • Pressing the accelerator key combination can trigger a command button's Click
    event.





NOTE: Not all of your application's events come from the user's actions. You
can trigger events with Visual Basic code. For example, you could ask your user to
press a command button when the user is ready to see a computed total. The command
button's Click event procedure will compute and print the total. However,
after a certain period of time, your code can trigger that same Click event
for the command button. Therefore, the total eventually appears with or without the
user's clicking of the command button.





Writing Event Procedures


Remember that event procedures contain Visual Basic code. The event procedures
are sections of code that handle a particular control's event. One control might
have several event procedures if you want to respond to several different kinds of
events for that control.


Visual Basic uses an event procedure's name to determine these two things about
the procedure:


  • Which control will trigger the procedure
  • Which event will trigger the procedure

Here is the format of all event procedure names:
ControlName_EventName ( ) 

The underscore separates the control name from the event name and is required. All
event procedures are named this way. Therefore, an event procedure namedcmdExit_DblClick
()
executes if and only if the command button named cmdExit's event
named DblClick occurs.

You'll eventually fill some event procedure parentheses with values after you
learn more about Visual Basic programming. Even if the parentheses are left blank,
as they were in the application you created yesterday, the parentheses are still
required. The parentheses also offer a way to distinguish event procedure names from
control names, even though the parentheses are not part of the actual name.


The code inside the cmdExit_DblClick () event procedure executes only
if the user double-clicks the command button named cmdExit. If this were
the only event procedure in the application, the application would ignore every other
event that takes place. If the user clicked the Exit command button, for example,
nothing would happen, because a click is different from a double-click.


Almost every event procedure you write while you learn Visual Basic will begin
with the words Private Sub. The Private keyword is optional; if
you don't specify Private, Visual Basic assumes that the event procedure
is private.


Visual Basic supports two kinds of procedures: functions and subroutines.
All event procedures will be subroutines. The body of an event procedure can be one
to several hundred lines long, although it's best to keep procedures as short as
possible. If you find yourself writing an extremely long procedure, consider breaking
it down into multiple, smaller procedures to make maintenance easier later on. Listing
3.1 is a sample of what cmdExit_DblClick () might look like if it appeared
inside an application.


LISTING 3.1. AN EVENT PROCEDURE THAT OCCURS WHEN THE USER DOUBLE-CLICKS THE COMMAND
BUTTON.


1: Private Sub cmdExit_DblClick ( ) 
2: lblTitle.Caption = "New Page"
3: intTotal = intCustNum + 1
4: End Sub





NOTE: You'll see numbers such as those to the left of Listing 3.1's code throughout
the rest of the book's listings. The numbers are not part of the program; they are
for reference only as you learn to program. If the text needs to refer to a line
of code, the number to the left of the line makes for an easy reference.



NEW TERM: A function acts like a baseball pitcher because a function
always sends a value, called the return value, to somewhere else in the program.
The keyword Function indicates that a procedure is a function and not a
subroutine. A subroutine, indicated by the Sub keyword, does not
send a return value, but it does perform work through its code. Event procedures
are always subroutines; you'll use functions for other kinds of work. You'll learn
much more about the differences between functions and subroutines as you progress
through these 21 days.


The first line of this event procedure tells much about the event procedure. From
the first line, you know the procedure is private (available only to the current
application module). You also know that the event procedure is a subroutine, so no
value is returned anywhere. The event procedure is for the command button (indicated
by the prefix cmd) that the developer named cmdExit. You know the
event procedure responds only to double-clicks that occur on this command button.


The body of the event procedure is two lines long. You don't have to understand
anything in the body at this time. The last line of event procedures always finalizes
the procedure and lets you and Visual Basic know where the procedure is to end. (All
functions end, as you can probably guess, with the End Function statement.)


Remember that you enter all code from the Code window. The Code window acts like
a simple word processor. When you are ready to write an event procedure, you can
get to the Code window in several ways. You can select the control for which you
want to write an event procedure for and select View, Code, or you can click the
Project window's View Object toolbar button.





NOTE: If Visual Basic guesses wrongly, and you want to write an event procedure
for an event that differs from the one Visual Basic supplies, you can change the
event name, perhaps to cmdHappy_DblClick (), and complete the event.



An even easier way is to double-click any control or form inside the Form window
editing area. Visual Basic automatically opens the Code window for that object, guesses
at the kind of event you want to write (using the most common event for that particular
control), and writes the event's first and last lines for you! That's what happened
in yesterday's application when you double-clicked the command button. Visual Basic
decided that the most common event for a command button is the Click event
and displayed the Code window with these two lines for you:


Private Sub cmdHappy_Click () 
End Sub

Visual Basic even placed the text cursor between the two lines, so you could type
the body of the event procedure! After you finish the event procedure, you can write
another event procedure below that one (if you do, you are responsible for the first
and last line of the event procedures that you add) or click the Project window's
View Object button once again to return to the Form window.

Figure 3.8 shows a Code window that lists the code for several event procedures.
The Code window not only separates procedures for you, it also supports routine Windows
Copy, Cut, and Paste operations. Unlike a word processor, the Code window will not
wrap lines because each statement of a Visual Basic program must reside on its own
line. You can continue extra long lines down to the next line if you place an underscore
at the end of the first line to let Visual Basic know that the statement continues
on the next line. With the underscore, Visual Basic treats the two lines as one long
continuous line; but the broken lines are easier for you to read because you can
see all the code without scrolling the Code window left and right.


FIGURE 3.8. The Code window acts like a word processor for your procedures.


Using Bonus Projects


You've just read through a lot of theory. Today should have answered some questions
for you, but perhaps it generated additional ones. To help put things into perspective,
Bonus Project 1, "Controls, Properties, and Events," appears between today's
and tomorrow's lessons. You'll walk through the creation of another application from
scratch so that you can put today's theory to practice. Although you won't receive
as much detailed instructions as you did for yesterday's application, you don't need
as much detail now that you are more familiar with the nature of Visual Basic. Throughout
this 21-day tutorial, Bonus Projects will pop up between some of the chapters to
reinforce your learning. Consider them homework for the next day.

Summary


Today's lesson was more theory than the first two were. You now should understand
controls, properties, and events better than before. Procedures should also be less
confusing, even though you've yet to learn any Visual Basic code. An event procedure
must exist for each control and event that you want to respond to in your program.
Without an event procedure, an event gets ignored.

Tomorrow's lesson teaches you how to add menus to your applications so that your
users can more easily control the programs you write.

Q&A



Q Why do we need to indent the body of event procedures?

A Actually, you need to indent the body of all procedures. The indention
is not required, but it helps you distinguish events from one another in long lines
of code. Although the Code window does a good job of separating procedures from one
another with dividing lines, you might print a program listing for study and analysis,
and the indention will help keep your eyes focused on individual procedures.



Q Can I make up new names for event procedures?

A The only way to change the name of an event procedure is to first change
the name of the control that triggers the procedure. Remember that the special name
format of event procedures lets Visual Basic determine which controls and which events
should trigger the event procedures. You'll be able to make up many of the subroutine
and function procedure names you write that are not event procedures, but you are
stuck using the event procedure names that correspond to the model described today.

Workshop


The Workshop provides quiz questions to help you solidify your understanding of the
material covered and exercises to provide you with experience in using what you've
learned. You should understand the quiz and exercise answers before continuing to
the next chapter. Appendix A, "Answers to Exercises," provides the answers.

Quiz



1. What is an accelerator key?



2. True/False. Properties support multiple events.



3. Why would you assign the Cancel event to a command button?



4. How do you know which control contains the focus?



5. How does the user move the focus from control to control?



6. What property determines the focus order?



7. Is LoadPicture () a subroutine, function, or event procedure (you
may have to guess at this)?



8. True/False. Visual Basic automatically generates the first and last lines
for the Click event procedure when you double-click a control inside the
Form window editing area.



9. True/False. You can trigger a user event, such as DblClick, from
Visual Basic code.



10. What is the purpose for the PasswordChar property?

Exercises



1. Write the first line for a form's Load event procedure. The
form's name is frmMyApp.



2. Bug Buster: Why can't the following be an event procedure?
1: Private Function txtGetName_KeyDown () 
2: ` Start the report
3: Call ReportPrint
4: lblWarning.Caption = "Get ready..."
5: End Function

3. Create an application with three multiline text boxes. Make the text
boxes tall enough to display three or four lines of text. Give the first one a vertical
scrollbar, the second a horizontal scrollbar, and the third one both kinds of scrollbars.
In all three text boxes, supply the default text Type here. In addition
to the text boxes, include an Exit command button, so the user can press Alt+X to
terminate the program.



Table of Contents







Sams TY VB 6 in 21 Days - Table of Contents


Sams Teach Yourself Visual Basic 6 in 21 Days



INTRODUCTION

WEEK 1 - AT A GLANCE



  • DAY 1 - WELCOME TO VISUAL BASIC

    • Visual Basic's Background
    • Why Write Programs?
    • Creating Your First Program
    • Event-Driven Programming
    • Summary
    • Q&A
    • Workshop




  • DAY 2 - WORKING WITH VISUAL BASIC

    • Understanding the Visual Basic Environment
    • Getting Help
    • Getting Used to the Screen
    • Creating an Application from Scratch
    • Summary
    • Q&A
    • Workshop




  • DAY 3 - MANAGING CONTROLS

    • Studying Controls
    • Control Focus
    • Event Procedures
    • Using Bonus Projects
    • Summary
    • Q&A
    • Workshop




  • BONUS PROJECT 1 - CONTROLS, PROPERTIES, AND EVENTS

    • The Visual Elements
    • Adding the Code
    • Analysis




  • DAY 4 - CREATING MENUS

    • Using the Application Wizard for Menus
    • Learning About Menus
    • Introducing the Menu Editor
    • Working with the Menu Editor
    • Summary
    • Q&A
    • Workshop




  • DAY 5 - ANALYZING VB DATA

    • A Few Preliminaries
    • Working Inside the Code Window
    • The Data in Visual Basic
    • Working with Variables
    • Using Variable Storage
    • Visual Basic's Operators
    • Analyzing the Order of Operators
    • Summary
    • Q&A
    • Workshop




  • BONUS PROJECT 2 - VARIABLES AND EXPRESSIONS

    • Analysis




  • DAY 6 - CONTROLLING PROGRAMS

    • Conditional Operators
    • Conditional Data
    • Combining Conditional Operators with Logical Operators
    • The If Statement Uses Conditional Operators
    • Completing the If with Else
    • An Early Exit
    • Nesting If...Else Statements
    • Selecting with Select Case
    • Repeat Code with Loops
    • Summary
    • Q&A
    • Workshop




  • DAY 7 - ADVANCED KEYBOARD AND SCREEN SUPPORT

    • Introduction to Internal Functions
    • Let the User Respond with MsgBox()
    • Getting Input with InputBox()
    • Handling the Keyboard
    • Additional Controls
    • Summary
    • Q&A
    • Workshop




  • BONUS PROJECT 3 - USER INPUT AND CONDITIONAL LOGIC

    • Creating the Initial Form
    • The Startup Form's Analysis
    • Creating the Check Box Form
    • The Check Box Form's Analysis
    • Creating the Option Button Form
    • The Option Button Form's Analysis


WEEK 1 - IN REVIEW


WEEK 2 - AT A GLANCE



  • DAY 8 - THE NATURE OF VB PROGRAMS

    • Mastering Program Structure
    • Calling General Procedures
    • Internal Functions
    • Summary
    • Q&A
    • Workshop




  • DAY 9 - THE DIALOG BOX CONTROL

    • The Need for a Common Dialog Box
    • Adding the Common Dialog Box Control
    • Working with the Common Dialog Box Control
    • Producing the Color Dialog Box
    • Handling the Cancel Button
    • Producing the Font Dialog Box
    • Help with Setting Controls
    • Producing File Open Dialog Boxes
    • Producing the File Save Dialog Box
    • Producing the Print Dialog Box
    • The Help Dialog Box
    • Summary
    • Q&A
    • Workshop




  • DAY 10 - ADDING POWER WITH THE MOUSE AND CONTROLS

    • Responding to the Mouse
    • List Box Controls
    • The Timer Control
    • Working with Arrays
    • Summary
    • Q&A
    • Workshop




  • BONUS PROJECT 4 - MULTIPLE LIST BOXES

    • Preparing for Multiple Selections
    • Adding the Code
    • Analysis




  • BONUS PROJECT 5 - PRACTICE WITH THE MOUSE

    • Changing the Mouse Icon
    • Programming the Mouse
    • Entering the Code
    • Analysis
    • Implementing Automatic Drag-and-Drop
    • Implementing Manual Drag-and-Drop




  • DAY 11 - WORKING WITH FORMS

    • Properties, Events, and Methods
    • Form Collections
    • Placing Text on Forms
    • Creating New Properties for Forms
    • Multiple Forms
    • Placing Toolbars on Forms
    • Adding Coolbars
    • Summary
    • Q&A
    • Workshop




  • DAY 12 - INTERACT WITH FILES

    • Working with Files
    • Working with Sequential-Access Files
    • Working with Random-Access Files
    • Using the File Controls
    • Summary
    • Q&A
    • Workshop
    • Quiz




  • BONUS PROJECT 6 - READING AND WRITING FILES

    • Creating the Interface
    • Entering the Code
    • Analysis




  • DAY 13 - PRINTING VB OUTPUT

    • Printer-Based Objects
    • Controlling the Output
    • Printing Your Forms
    • PrintForm Warnings
    • Don't Surprise Your Users
    • Summary
    • Q&A
    • Workshop




  • DAY 14 - INTRODUCING VB GRAPHICS AND MULTIMEDIA

    • Comparing the Picture Box and Image Controls
    • The Drawing Controls
    • Drawing with Methods
    • The Multimedia Control
    • Playing Video Clips
    • Summary
    • Q&A
    • Workshop




  • BONUS PROJECT 7 - WORKING WITH SCROLLBARS

    • Introducing Scrollbars
    • Building an Application
    • Entering the Code
    • Analysis


WEEK 2 - IN REVIEW


WEEK 3 - AT A GLANCE



  • DAY 15 - USING FORM TEMPLATES

    • About Form Templates
    • The Supplied Form Templates
    • Adding Your Own Form Templates
    • Summary
    • Q&A
    • Workshop




  • DAY 16 - OBJECTS AND VISUAL BASIC

    • OLE for Outside Objects
    • Working with Objects
    • The Object Browser
    • Summary
    • Q&A
    • Workshop




  • DAY 17 - ACTIVEX CONTROLS

    • The Need for ActiveX
    • Adding ActiveX Controls to a Project
    • ActiveX Automation
    • Creating Your Own ActiveX Controls
    • Summary
    • Q&A
    • Workshop




  • BONUS PROJECT 8 - ELEMENTS THAT SPRUCE UP APPS

    • The Application's Goal
    • Creating the Primary Form
    • Adding the Opening Form's Code
    • Analysis
    • Creating the About Box




  • DAY 18 - INTERACTING WITH DATA

    • Database Data and Visual Basic
    • Learn the Terms
    • Obtaining Sample Data
    • The Data Control
    • Using the VB Application Wizard
    • Summary
    • Q&A
    • Workshop




  • BONUS PROJECT 9 - ADO CONTROLS

    • The Application's Goal
    • Creating the Initial Form
    • Connecting the ADO Control to the Data
    • Finding Data
    • Traversing the Data
    • Table Updates
    • Concluding with the ADO Control




  • DAY 19 - ADDING INTERNET ACCESS

    • The Internet Wizard
    • Looking at Some Internet Controls
    • Preview of Advanced Issues
    • Summary
    • Q&A
    • Workshop




  • DAY 20 - PROVIDING HELP

    • ToolTip and What's This? Help
    • How Help Fits into an Application
    • Adding What's This? Help
    • Summary
    • Q&A
    • Workshop




  • DAY 21 - DISTRIBUTING YOUR APPLICATIONS

    • Debugging and Testing
    • Using the Debugger
    • Distributing Your Application
    • Summary
    • Q&A
    • Workshop


WEEK 3 - IN REVIEW


BONUS CHAPTERS



  • DAY 22 - MULTIDIMENSIONAL ARRAYS

    • Introduction to Multidimensional Arrays
    • Using the Grid Control
    • Summary
    • Q&A
    • Workshop




  • DAY 23 - THE WINDOWS API

    • The Windows API
    • The Nature of DLLs
    • Using the Declare Statement
    • Calling a Simple API Routine
    • Calling a Different API
    • Locating the Windows Folder
    • Summary
    • Q&A
    • Workshop


APPENDIXES



  • APPENDIX A - ANSWERS TO EXERCISES



    • Day 1, "Welcome to Visual Basic"
    • Day 2, "Working with Visual Basic"
    • Day 3, "Managing Controls"
    • Day 4, "Creating Menus"
    • Day 5, "Analyzing VB Data"
    • Day 6, "Controlling Programs"
    • Day 7, "Advanced Keyboard and Screen Support"
    • Day 8, "The Nature of VB Programs"
    • Day 9, "The Dialog Box Control"
    • Day 10, "Adding Power with the Mouse and Controls"
    • Day 11, "Working with Forms"
    • Day 12, "Interact with Files"
    • Day 13, "Printing VB Output"
    • Day 14, "Introducing VB Graphics and Multimedia"
    • Day 15, "Using Form Templates"
    • Day 16, "Objects and Visual Basic"
    • Day 17, "ActiveX Controls"
    • Day 18, "Interacting with Data"
    • Day 19, "Adding Internet Access"
    • Day 20, "Providing Help"
    • Day 21, "Distributing Your Applications"
    • Day 22, "Multidimensional Arrays"
    • Day 23, "The Windows API"




  • APPENDIX B - OPERATOR PRECEDENCE



  • APPENDIX C - ASCII TABLE



  • INDEX



Customer Reviews

Most Helpful Customer Reviews

See All Customer Reviews