Using Visual Basic's Standard Controls
Using Visual Basic's Standard Controls
—1
1
Control Categories
There are three broad categories of controls in Visual Basic:
· Intrinsic controls, such as the command button and frame controls. These controls
are contained inside the Visual Basic .exe file. Intrinsic controls are always
included in the toolbox, unlike ActiveX controls and insertable objects, which
can be removed from or added to the toolbox.
· ActiveX controls, which exist as separate files with a .ocx file name extension.
These include controls that are available in all editions of Visual Basic (data-
bound grid, combo box, list controls, and so on) and those that are available
only in the Professional and Enterprise editions (such as Listview, Toolbar,
—2
Intrinsic Controls
The following table summarizes the intrinsic controls found in the Visual Basic
toolbox.
Icon Control name Class name Description
Check box CheckBox Displays a True/False or Yes/No
option. You can check any number of
check boxes on a form at one time.
Combo box ComboBox Combines a text box with a list box.
Allows a user to type in a selection or
select an item from a drop-down list.
Command button CommandButton Carries out a command or action
when a user chooses it.
Data Data Enables you to connect to an existing
database and display information
from it on your forms.
Directory list box DirListBox Displays and allows a user to select
directories and paths.
Drive list box DriveListBox Displays and allows a user to select
valid disk drives.
File list box FileListBox Displays and allows a user to select
from a list of files.
—3
—4
4
The following table summarizes the standard ActiveX controls available in the
Learning edition of Visual Basic.
Icon Control name Class name Description
Common dialog CommonDialog Provides a standard set of dialog
boxes for operations such as opening
and saving files, setting print options,
and selecting colors and fonts.
Data-bound combo box DBCombo Provides most of the features of the
standard combo box control, plus
increased data access capabilities.
Apex data-bound grid DBGrid A spreadsheet-like bound control that
displays a series of rows and columns
representing records and fields from a
Recordset object.
Data-bound list box DBList Provides most of the features of the
standard list box control, plus
increased data access capabilities.
Microsoft FlexGrid MSFlexGrid Similar to the DBGrid control, but
has additional formatting, grouping,
and binding features, as well as
customization options.
7
For More Information See "Using the ActiveX Controls" for more information about
the ActiveX controls available in the Professional and Enterprise versions of Visual
Basic.
8
Adding and Removing ActiveX Controls
You move ActiveX controls to and from the toolbox using the following procedures.
—5
—6
—7
—8
The Name and Index property values for the control arrays in the Calculator example are listed in the
following table.
Number(n) Operator(n)
0 = Number(0) + = Operator(1)
1 = Number(1) – = Operator(2)
2 = Number(2) X = Operator(3)
3 = Number(3) / = Operator(4)
4 = Number(4) = = Operator(5)
5 = Number(5)
6 = Number(6)
7 = Number(7)
8 = Number(8)
9 = Number(9)
15
Notice how each control is referred to with the syntax object(index). You specify the
index of a control when you create it. In fact, specifying any index for a control at
design time makes that control part of an array.
—9
—10
—11
11
The following table lists the property settings for the objects in the application.
Object Property Setting
Form Caption Control Array Example
Picture box Name picDisplay
Label Caption Select an option button to display
a new color
Option1 Name optButton
Index 0
Option2 Name optButton
Index 1
First command button Name cmdAdd
Caption &Add
Second command button Name cmdDelete
Caption &Delete
Third command button Name cmdClose
Caption &Close
22
Events in the Control Array Application
Next, you need to add the event procedures for the option buttons and command
buttons. Start by adding the form declaration:
Dim MaxId As Integer
23
—12
—13
12
The check box control is similar to the option button control in that each is used to
indicate a selection that is made by the user. They differ in that only one option
button in a group can be selected at a time. With the check box control, however,
any number of check boxes may be selected.
For More Information See "Selecting Individual Options with Check Boxes" in
"Forms, Controls, and Menus" for a simple demonstration of the check box control.
27
The Value Property
The Value property of the check box control indicates whether the check box is
checked, unchecked, or unavailable (dimmed). When selected, the value is set to 1.
For example:
13
The following table lists the values and equivalent Visual Basic constants that are
used to set the Value property.
Setting Value Constant
Unchecked 0 vbUnchecked
Checked 1 vbChecked
Unavailable 2 vbGrayed
28
The user clicks the check box control to indicate a checked or unchecked state. You
can then test for the state of the control and program your application to perform
some action based on this information.
By default, the check box control is set to vbUnchecked. If you want to preselect
several check boxes in a series of check boxes, you can do so by setting the Value
property to vbChecked in the Form_Load or Form_Initialize procedures.
You can also set the Value property to vbGrayed to disable the check box. For
example, you may want to disable a check box until a certain condition is met.
—14
You can toggle selection of the check box control by adding an ampersand character
before a letter in the Caption property to create a keyboard shortcut. For example:
14
In this example, pressing the ALT+C key combination toggles between the checked
and unchecked states.
—15
15
Combo boxes present a list of choices to the user. If the number of items exceeds
what can be displayed in the combo box, scroll bars will automatically appear on the
control. The user can then scroll up and down or left to right through the list.
—16
17
Drop-down Combo Box
With the default setting (Style = 0 – Dropdown Combo), a combo box is a drop-
down combo box. The user can either enter text directly (as in a text box) or click
the detached arrow at the right of the combo box to open a list of choices. Selecting
one of the choices inserts it into the text portion at the top of the combo box. The
user also can open the list by pressing ALT+ DOWN ARROW when the control has the
focus.
—17
18
Adding Items at Design Time
You can also enter items into the list at design time by setting the List property in
the Properties window of the combo box control. When you select the List property
option and then click the down arrow, you can type list items and then press the
CTRL+ENTER key combination to start a new line.
You can only add items to the end of the list. So, if you want to alphabetize the list,
set the Sorted property to True. See "Sorting a List" below for more information.
—18
19
Sorting a List
You can specify that items be added to a list in alphabetical order by setting the
Sorted property to True and omitting the index. The sort is not case-sensitive; thus,
the words "chardonnay" and "Chardonnay" are treated the same.
When the Sorted property is set to True, using the AddItem method with the index
argument can lead to unpredictable, unsorted results.
Removing Items
You can use the RemoveItem method to delete items from a combo box.
RemoveItem has one argument, index, which specifies the item to remove:
box.RemoveItem index
37
The box and index arguments are the same as for AddItem.
For example, to remove the first entry in a list, you would add the following line of
code:
Combo1.RemoveItem 0
38
To remove all list entries in a combo box, use the Clear method:
Combo1.Clear
39
Getting List Contents with the Text Property
Usually, the easiest way to get the value of the currently selected item is to use the
Text property. The Text property corresponds to whatever is entered in the text box
portion of the control at run time. This can be either a selected list item or a string
that a user types in the text box.
—19
20
Most Visual Basic applications have command buttons that allow the user to simply
click them to perform actions. When the user chooses the button, it not only carries
out the appropriate action, it also looks as if it's being pushed in and released and is
therefore sometimes referred to as a push button.
For More Information See "Clicking Buttons to Perform Actions" in "Forms, Controls,
and Menus" for a simple demonstration of the Command Button control.
45
Adding a Command Button to a Form
You will likely use one or more command buttons in your application. To add
command buttons to a form, draw them on as you would any other control.
Command buttons can be sized with the mouse or by setting their Height and Width
properties.
—21
· If the command button is the default Cancel button for the form, then pressing
ESC chooses the button, even if you change the focus to another control.
21
The Value Property
Whenever the command button is selected, its Value property is set to True and the
Click event is triggered. False (default) indicates the button isn't chosen. You can use
the Value property in code to trigger the command button's Click event. For
example:
cmdClose.Value = True
47
The Click Event
When clicked, the command button's Click event is triggered and the code you've
written in the Click event procedure is invoked.
Clicking a command button control also generates the MouseDown and MouseUp
events. If you intend to attach event procedures for these related events, be sure that
their actions don't conflict. The order in which these three events occur varies from
control to control. In the command button control, these events occur in this order:
MouseDown, Click, MouseUp.
—22
22
The common dialog control provides an interface between Visual Basic and the
routines in the Microsoft Windows dynamic-link library Commdlg.dll. To create a
dialog box using this control, Commdlg.dll must be in your Microsoft Windows
\System directory.
You use the common dialog control in your application by adding it to a form and
setting its properties. The dialog displayed by the control is determined by the
methods of the control. At run time, a dialog box is displayed or the Help engine is
executed when the appropriate method is invoked; at design time, the common
dialog control is displayed as an icon on a form. This icon can't be sized.
The common dialog control allows you to display these commonly used dialog
boxes:
· Open
· Save As
· Color
· Font
· Print
—23
—24
26
To display the Open dialog box
14 Specify the list of file filters that are displayed in the Files of type list box.
4You can do this by setting the Filter property using the following format:
description1 | filter1 | description2 | filter2...
27
5Description is the string displayed in the list box — for example, "Text Files
(*.txt)." Filter is the actual file filter — for example, "*.txt." Each
description | filter set must be separated by a pipe symbol (|).
15 Use the ShowOpen method to display the dialog box.
28
After the user chooses a file, use the FileName property to get the name of the
selected file.
With all the common dialog boxes, when the CancelError property is True, an error
is generated when the user clicks the dialog box's Cancel button. You detect that the
Cancel button was pressed by trapping the error when the dialog box is displayed.
The following code displays an Open dialog box and uses the selected file name as
an argument to a procedure that opens a file:
Private Sub mnuFileOpen_Click ()
' CancelError is True.
On Error GoTo ErrHandler
' Set filters.
CommonDialog1.Filter = "All Files (*.*)|*.*|Text _
Files (*.txt)|*.txt|Batch Files (*.bat)|*.bat"
' Specify default filter.
—25
ErrHandler:
' User pressed Cancel button.
Exit Sub
End Sub
50
29
To display the Color dialog box
16 Set the Flags property for the common dialog control to the Visual Basic constant
cdlCCRGBInit.
17 Use the ShowColor method to display the dialog box.
30
—26
ErrHandler:
' User pressed Cancel button.
Exit Sub
End Sub
51
—27
31
To display the Font dialog box
18 Set the Flags property to one of the following Visual Basic constant values:
· cdlCFScreenFonts (screen fonts)
· cdlCFPrinterFonts (printer fonts)
· cdlCFBoth (for both screen and printer fonts)
1
1Caution You must set the Flags property to one of these values before displaying the
Font dialog box. Otherwise, the error No fonts exist occurs.
1
19 Use the ShowFont method to display the dialog box.
32
The following code sets the font properties for a text box based on a user's selections
in the Font dialog box:
Private Sub Command1_Click ()
' Set Cancel to True.
CommonDialog1.CancelError = True
On Error GoTo ErrHandler
' Set the Flags property.
CommonDialog1.Flags = cdlCFBoth Or cdlCFEffects
' Display the Font dialog box.
—28
—29
33
To display the Print dialog box
20 Set any desired default settings for the dialog by setting the appropriate Print
dialog properties.
6For example, to display 2 in the Copies box when the dialog is displayed, set the
Copies property to 2:
1CommonDialog1.Copies = 2
34
21 Use the ShowPrinter method to display the Print dialog box.
35
The following code displays the Print dialog box when the user clicks the
Command1 command button:
Private Sub Command1_Click ()
Dim BeginPage, EndPage, NumCopies, i
' Set Cancel to True.
CommonDialog1.CancelError = True
On Error GoTo ErrHandler
' Display the Print dialog box.
CommonDialog1.ShowPrinter
' Get user-selected values from the dialog box.
BeginPage = CommonDialog1.FromPage
EndPage = CommonDialog1.ToPage
NumCopies = CommonDialog1.Copies
For i = 1 to NumCopies
—30
ErrHandler:
' User pressed Cancel button.
Exit Sub
End Sub
59
—31
37
The data-bound list, data-bound combo, data-bound grid, and Microsoft FlexGrid
controls are all capable of managing sets of records when bound to a data control.
All of these controls permit several records to be displayed or manipulated at once.
The intrinsic picture, label, text box, check box, image, OLE container, list box and
combo box controls are also data-aware and can be bound to a single field of a
Recordset managed by the data control. Additional data-aware controls like the
masked edit and rich text box controls are available in the Professional and
Enterprise editions and from third-party vendors.
Figure 7.17 The data-bound list box and combo box controls
38
The Data-Bound Grid Control
The data-bound grid control is a spreadsheet-like bound control that displays a series
of rows and columns representing records and fields from a Recordset object.
39
The data-bound grid control is functionally similar to the Microsoft FlexGrid control.
The Microsoft FlexGrid control, however, provides read-only data binding,
—32
—33
41
File-system controls obtain all their information from the operating system
automatically; you can access this information or determine what is displayed by
each control through its properties. For example, the contents of the current working
directory is displayed by default (that is, the directory from which the application
was launched, or what became the current directory as the result of a ChDir
statement).
Your application can also display a list of the files with names matching a pattern,
such as *.frm. Simply draw a file list box on the form and set its Pattern property to
*.frm. You can specify the Pattern property at run time with the following code:
File1.Pattern = "*.FRM"
62
The file-system controls give you the flexibility that is not available with the
common dialog control. You can mix and match them in a variety of ways, and you
control their appearance and how they interact.
If your goal is simply to allow users to open and save files, a common dialog control
provides a ready-to-run set of dialog boxes for these and other operations. These are
the same dialog boxes used by many other Microsoft Windows – based applications,
so they provide a standardized look-and-feel. They also recognize network drives
when they're available.
For More Information See "Using the Common Dialog Control" earlier in this chapter
for more information.
63
—34
—35
42
Setting the Current Directory
Use the Path property of the directory list box to set or return the current directory in
the box (ListIndex = – 1). For example, if you assign "c:\payroll" to Drive1.Path in
Figure 7.21, the \Payroll directory becomes selected as the current working
directory.
Similarly, you can assign the Drive property of the drive list box to the Path property
of the directory list box:
Dir1.Path = Drive1.Drive
66
When this assignment is executed, the directory list box displays all the available
directories and subdirectories on that drive. By default, the directory list box also
displays all directories above, and any subdirectories immediately below, the current
directory of a drive assigned to the Dir1.Path property. The directory list box doesn't
set the current directory at the operating system level; it merely highlights the
directory and gives it the ListIndex value of – 1.
To set the current working directory, use the ChDir statement. For example, the
following statement changes the current directory to the one displayed in the
directory list box:
ChDir Dir1.Path
67
In an application that uses file controls, you can set the current directory to the
directory where the application's executable (.exe) file is located with the
Application object:
ChDrive App.Path ' Set the drive.
ChDir App.Path ' Set the directory.
68
Note The Path property is available only at run time, not at design time.
69
Clicking a Directory Item
When a user clicks an item in a directory list box, that item is highlighted. When an
item is double-clicked, it is assigned to the Path property, its ListIndex property gets
—36
GoHigher = 0
' Dir1.List(x) returns empty string if the directory
' doesn't exist.
Do Until Dir1.List(GoHigher) = ""
GoHigher = GoHigher - 1
Loop
' Convert to positive number, if desired.
LevelsAbove = Abs(GoHigher)
70
—37
—38
46
The following table summarizes the controls in Seek.frm from the WinSeek
application.
Control Property Setting
Drive list box Name drvList
Directory list box Name dirList
File list box Name filList
Pattern *.*
First command button Name cmdSearch
Caption &Search
Default True
Second command button Name cmdExit
Caption E&xit
List box Name lstFoundFiles
75
—39
—40
For More Information See "Debugging Your Code and Handling Errors" for more
information.
79
The Directory List Box's Change Event
If the user double-clicks an item in the directory list box, or if the Path property of
dirList is changed in code (as in the drvList_Change procedure), the dirList_Change
event is initiated. The following code responds to that event:
Private Sub dirList_Change ()
' Update file list box to synchronize with the
' directory list box.
filList.Path = dirList.Path
End Sub
80
This event procedure assigns the Path property of the dirList box to the Path property
of the filList box. This causes a PathChange event in the filList list box, which is
redrawn; you don't need to add code to the filList_PathChange procedure, because in
this application, the event chain ends in the filList list box.
—41
48
The Microsoft FlexGrid control supports the following features:
· Read-only data binding.
· Ability to pivot data between columns and rows.
· Automatic regrouping of data during column adjustment.
· Adaptation to existing Visual Basic code for the data-bound grid (DBGrid).
· Ability of each cell to contain text, a picture, or both.
· Changing of current cell text in code or at run time.
· Ability to read data automatically when assigned to a data control.
—42
—43
Sub DoSort ()
Fg1.Col = 0
Fg1.ColSel = Fg1.Cols - 1
—44
—45
—46
—47
—48
Sub Fg2_DblClick ()
MSFlexGridEdit Fg2, txtEdit, 32 ' Simulate a space.
End Sub
92
To initialize the text box and to pass the focus from the Microsoft FlexGrid control
to the text box, add the following routine:
Sub MSFlexGridEdit (MSFlexGrid As Control, _
Edt As Control, KeyAscii As Integer)
—49
—50
Sub Fg2_LeaveCell ()
If txtEdit.Visible = False Then Exit Sub
Fg2 = txtEdit
txtEdit.Visible = False
End Sub
95
At run time, data can be entered into individual cells as in this example:
58
—51
—52
61
Add Collapsing and Expanding Functionality
To add functionality which allows the row headings to be expanded or collapsed, add
the following code to the control's DblClick event procedure:
Sub Fg3_DblClick ()
Dim i As Integer, r As Integer
—53
62
—54
63
In most cases, you will use the frame control passively — to group other controls —
and will have no need to respond to its events. You will, however, most likely
change its Name, Caption, or Font properties.
For More Information See "Grouping Options with Option Buttons" in "Forms,
Controls, and Menus" for a simple demonstration of using the frame control to group
option buttons.
100
Adding a Frame Control to a Form
When using the frame control to group other controls, first draw the frame control,
and then draw the controls inside of it. This enables you to move the frame and the
controls it contains together.
64
—55
65
66
The horizontal and vertical scroll bar controls are not the same as the built-in scroll
bars found in Windows or those that are attached to text boxes, list boxes, combo
boxes, or MDI forms within Visual Basic. Those scroll bars appear automatically
whenever the given application or control contains more information than can be
displayed in the current window size (or, in the case of text boxes and MDI forms,
when the ScrollBars property is also set to True).
—56
—57
67
Start by creating a new project and then draw two picture boxes, a horizontal scroll
bar, and a vertical scroll bar on the form, as shown in Figure 7.28.
The form's Form_Load event is used to set the scale mode, to size the child picture
box within the parent picture box, to position and size the horizontal and vertical
scroll bars, and then to load a bitmap graphic. Add the following code to the form's
Form_Load event procedure:
Private Sub Form_Load()
—58
End Sub
104
The horizontal and vertical scroll bars' Change event is used to move the child
picture box up and down or left and right within the parent picture box. Add the
following code to the Change event of both scroll bar controls:
Private Sub HScroll1_Change()
Picture2.Left = -HScroll1.Value
End Sub
—59
68
Resizing the Form at Run Time
In the example described above, the viewable size of the graphic is limited by the
original size of the form. To resize the graphic viewport application when the user
adjusts the size of the form at run time, add the following code to the form's
Form_Resize event procedure:
Private Sub Form_Resize()
' When the form is resized, change the Picture1
' dimensions.
Picture1.Height = Form1.Height
Picture1.Width = Form1.Width
End Sub
106
—60
69
In addition, image controls respond to the Click event and can be used as a substitute
for command buttons, as items in a toolbar, or to create simple animations.
For More Information See "Lightweight Graphical Controls" in "Forms, Controls, and
Menus" for a simple demonstration of using the image control like a command
button. See "Creating Simple Animation" in "Working with Text and Graphics" for
more information on using the image control to create simple animations.
107
When to Use an Image Control Instead of a Picture Box Control
The image control uses fewer system resources and repaints faster than a picture box
control, but it supports only a subset of the picture box control's properties, events,
and methods. Both controls support the same picture formats. However, you can
stretch pictures in an image control to fit the control's size. You cannot do this with
the picture box control.
—61
—62
70
71
Labels are used in many instances, for many different purposes. Most commonly,
they are used to label controls that don't have their own Caption properties. For
example, you can use the label control to add descriptive labels to text boxes, list
boxes, combo boxes and so on. They can also be used to add descriptive text to a
form, for example, to provide the user with Help information.
You can also write code that changes the text displayed by a label control in
response to events at run time. For example, if your application takes a few minutes
to process a change, you can display a processing-status message in a label.
Because the label control cannot receive the focus, it can also be used to create
access keys for other controls.
Aligning Text
The Alignment property allows you to set the alignment of the text within the label
control to either Left Justify (0, the default) , Center (1), or Right Justify (2).
—63
—64
73
You can control the position, length, color, and style of line controls to customize
the look of applications. Figure 7.34 shows a line control used to graphically
separate the label containing the text "Company Name" from the rest of the form.
74
The line control has limited functionality and is intended for simple uses — display
and printing. Line segments cannot be joined to form other shapes, for instance. For
more advanced uses you need to use the line method.
For More Information See "Using Graphics Methods" in "Working with Text and
Graphics" for more information on drawing lines, rectangles, and filled-in boxes at
run time using the line method or for more information on drawing circles, ellipses,
and arcs at run time using the Circle method.
113
Setting Border Style and Color
You set the color and style of a line segment by using the BorderStyle and
BorderColor properties.
The BorderStyle property provides you with six line styles:
· Transparent
· Solid
· Dash
· Dot
· Dash-Dot
· Dash-Dot-Dot
· Inside Solid
75
—65
—66
77
List boxes present a list of choices to the user. By default, the choices are displayed
vertically in a single column, although you can set up multiple columns as well. If
the number of items exceeds what can be displayed in the list box, scroll bars
automatically appear on the control. The user can then scroll up and down, or left to
right through the list. Figure 7.36 shows a single-column list box.
78
Data-Bound Features
Visual Basic includes both standard and data-bound versions of the list box control.
While both versions of the list box control allow you to display, edit, and update
information from most standard types of databases, the data-bound list provides
more advanced data access features. The data-bound list box control also supports a
different set of properties and methods than the standard list box control.
116
The Click and Double-Click Events
A recommended practice for list box events, especially when the list box appears as
part of a dialog box, is to add a command button to use with the list box. The Click
event procedure for this button should make use of the list-box selection, carrying
out whatever action is appropriate for your application.
Double-clicking an item in the list should have the same effect as selecting the item
and then clicking the command button. To do this, have the DblClick procedure for
the list box call the Click procedure for the command button:
Private Sub List1_DblClick ()
Command1_Click
End Sub
117
Or, set the value of the command button's Value property to True, which will
automatically invoke the event procedure:
Private Sub List1_DblClick ()
Command1.Value = True
End Sub
118
—67
79
Adding an Item at a Specified Position
To add an item to a list at a specific position, specify an index value for the new
item. For example, the next line of code inserts "Japan" into the first position,
adjusting the position of the other items downward:
List1.AddItem "Japan", 0
122
Notice that it is 0, not 1, that specifies the first item in a list (see Figure 7.38).
—68
80
Adding Items at Design Time
You can also enter items into the list at design time by setting the List property in
the Properties window of the list box control. When you select the List property
option and then click the down arrow, you can type list items and then press the
CTRL+ENTER key combination to start a new line.
You can only add items to the end of the list. So, if you want to alphabetize the list,
set the Sorted property to True. See "Sorting a List" below for more information.
Sorting a List
You can specify that items be added to a list in alphabetical order by setting the
Sorted property to True and omitting the index. The sort is not case-sensitive; thus,
the words "japan" and "Japan" are treated the same.
When the Sorted property is set to True, using the AddItem method with the index
argument can lead to unpredictable, unsorted results.
—69
—70
—71
81
The number of clients in the list box is displayed in a label that looks like a text box
(BorderStyle is set to 1-Fixed Single). This label is updated every time a client name
is added or removed. Because the Sorted property for the list box is set to True,
items are added to the list box in alphabetical order.
Create a form with a text box, a list box, three labels, and four command buttons.
The following table lists the property settings for the objects in the application.
Object Property Setting
Top text box Name txtName
Text (Empty)
Top label Name lblName
Caption &Name to add
List box Name lstClient
Sorted True
Bottom label Name lblClients
Caption # Clients
Number of clients label Name lblDisplay
(looks like a text box) Caption (Empty)
BorderStyle 1-Fixed Single
First command button Name cmdAdd
Caption &Add
Second command button Name cmdRemove
Caption &Remove
Third command button Name cmdClear
Caption C&lear
Fourth command button Name cmdClose
Caption &Close
134
—72
—73
82
If you draw the list box large enough to hold all the items in one column, the second
column will be empty; the other items will wrap, and horizontal scroll bars will
appear automatically only if the list box is not long enough. Try resizing the top list
box and adding additional list items to see how Visual Basic automatically handles
multiple columns.
The example uses the Selected property — a Boolean array containing the selection
status of a list box — to determine which items are selected. Each entry in the array
corresponds to a list item and is set to True if the item is selected, or False if it is not
selected. After the user selects items from the list, each array entry is checked to see
if it is set (True). If so, the entry is added to the second list, a normal single-column
list box, using the AddItem method.
Set the properties for the example as indicated in the following table.
Object Property Setting
Form Caption Multiple-Column List Box
—74
—75
83
The OLE container control is used to create a document-centered application. In
such an application, the user combines data from different applications to create a
single document. This type of application may be a word processor that allows the
user to enter text and then embed a spreadsheet or chart.
The OLE container control allows you to add objects from other applications to your
Visual Basic applications. With this control, you can:
· Create a placeholder in your application for an object. You can create the object
that appears within the OLE container control at run time, or you can change
an object you have placed in the OLE container control at design time.
· Create a linked object in your application.
· Bind the OLE container control to a database.
· Perform an action if the user moves, sizes, or updates the object in the OLE
container control.
· Create objects from data that was copied onto the Clipboard.
—76
85
While option button controls and check box controls may appear to function
similarly, there is an important difference: when a user selects an option button, the
other option button controls in the same group are automatically unavailable. In
contrast, any number of check box controls can be selected.
For More Information See "Grouping Options with Option Buttons" in "Forms,
Controls, and Menus" for a demonstration of the use of option buttons.
148
Creating Option Button Groups
You group option button controls by drawing them inside a container such as a frame
control, a picture box control, or a form. At run time, the user may select a single
option button from each distinct group of option buttons. For example, if you add
option buttons to a form and option buttons to a frame control on the form, you have
created two distinct groups of option buttons.
86
—77
87
The picture box control is similar to the image control in that each can be used to
display graphics in your application — each supports the same graphic formats. The
picture box control, however, contains functionality which the image control does
not, for example: the ability to act as a container for other controls and support for
graphics methods.
For More Information See "Working with Picture Boxes" "Forms, Controls, and
Menus" for a demonstration of the use of picture boxes.
152
Supported Graphic Formats
The picture box control can display picture files in any of the following formats:
bitmap, icon, metafile, enhanced metafile, or as JPEG or GIF files.
For More Information See "Using the Image Control" earlier in this chapter for
detailed descriptions of these graphic formats.
153
—79
Sizing a Picture
By default, graphics are loaded into a picture box at their original size, meaning that
if the graphic is larger than the control, the image will be clipped — the picture box
control does not provide scroll bars. To make a picture box control automatically
resize to display an entire graphic, set its AutoSize property to True. The control will
then size to the graphic — growing or shrinking.
Unlike the image control, the picture box control cannot stretch the image to fit the
size of the control.
For More Information See "Scroll Bar Controls Scenario: Creating a Scrollable
Graphics Viewport" earlier in this chapter for information on using picture boxes to
create a scrollable graphics viewport.
156
Using the Picture Box Control as a Container
You can use the picture box control as a container for other controls. For example,
since the picture box can be placed inside the internal area of a MDI form, it is often
used to manually create a toolbar or status bar.
157
Graphics Methods
Picture boxes, like forms, can be used to receive the output of graphics methods such
as Circle, Line, and Point. For example, you can use the Circle method to draw a
circle in a picture box by setting the control's AutoRedraw property to True.
—80
88
You can set the shape style, color, fill style, border color, and border style of any of
the shapes you draw on a form.
For simple uses, the shape control allows you to create a variety of shapes without
writing any code. For more advanced functionality you need to use the Line and
Circle methods.
For More Information See "Using Graphics Methods" in "Working with Text and
Graphics" for more information on drawing lines, rectangles, and filled-in boxes at
run time using the Line method or for more information on drawing circles, ellipses,
and arcs at run time using the Circle method.
162
—81
89
Fill and Line Styles
You can use the FillStyle and BorderStyle properties to set the fill style and border
style of any of the shapes you draw on a form.
The FillStyle property, like the Style property, provides you with a number of
predefined fill style patterns. These include: Solid, Transparent, Horizontal Line,
Vertical Line, Upward Diagonal, Downward Diagonal, Cross, and Diagonal Cross.
The BorderStyle property provides you with a number of predefined border styles.
These include: Transparent, Solid, Dash, Dot, Dash-Dot, Dash-Dot-Dot, and Inside
Solid.
164
Setting Color Attributes
The BackColor and FillColor properties allow you to add color to the shape and its
border.
—82
91
In general, the text box control should be used for editable text, although you can
make it read-only by setting its Locked property to True. Text boxes also allow you
to display multiple lines, to wrap text to the size of the control, and to add basic
formatting.
—83
Formatting Text
When text exceeds the boundaries of the control, you can allow the control to
automatically wrap text by setting the MultiLine property to True and add scroll bars
by setting the ScrollBars property to add either a horizontal or vertical scroll bar, or
both. Automatic text wrapping will be unavailable, however, if you add a horizontal
scroll bar because the horizontal edit area is increased by the presence of the scroll
bar.
When the MultiLine property is set to True, you can also adjust the alignment of the
text to either Left Justify, Center, or Right Justify. The text is left-justified by
default. If the MultiLine property is False, setting the Alignment property has no
effect.
For More Information See "Working with Text Boxes" for a demonstration of the
MultiLine, ScrollBar, and Alignment properties.
167
Selecting Text
You can control the insertion point and selection behavior in a text box with the
SelStart, SelLength and SelText properties.
For More Information See "Working with Text Boxes" in "Forms, Controls, and
Menus" for a demonstration of the SelStart, SelText, and SelLength properties.
168
Creating a Password Text Box
A password box is a text box that allows a user to type in his or her password while
displaying placeholder characters, such as asterisks. Visual Basic provides two text
box properties, PasswordChar and MaxLength, which make it easy to create a
password text box.
PasswordChar specifies the character displayed in the text box. For example, if you
want asterisks displayed in the password box, you specify * for the PasswordChar
property in the Properties window. Regardless of what character a user types in the
text box, an asterisk is displayed, as shown in Figure 7.48.
—84
92
With MaxLength, you determine how many characters can be typed in the text box.
After MaxLength is exceeded, the system emits a beep and the text box does not
accept any further characters.
—85
93
Each timer control has an Interval property that specifies the number of milliseconds
that pass between one timer event to the next. Unless it is disabled, a timer continues
to receive an event (appropriately named the Timer event) at roughly equal intervals
of time.
The Interval property has a few limitations to consider when you're programming a
timer control:
· If your application or another application is making heavy demands on the system
— such as long loops, intensive calculations, or drive, network, or port access
— your application may not get timer events as often as the Interval property
specifies.
· The interval can be between 0 and 64,767, inclusive, which means that even the
longest interval can't be much longer than one minute (about 64.8 seconds).
· The interval is not guaranteed to elapse exactly on time. To ensure accuracy, the
timer should check the system clock when it needs to, rather than try to keep
track of accumulated time internally.
· The system generates 18 clock ticks per second — so even though the Interval
property is measured in milliseconds, the true precision of an interval is no
more than one-eighteenth of a second.
—86
—87
95
At run time, the timer is invisible. The following table lists the property settings for
the Digital Clock application.
Control Property Setting
Label1 BorderStyle Fixed Single
Timer1 Interval 500 (half a second)
Timer1 Enabled True
177
The only procedure in this application is an event procedure for the timer:
Private Sub Timer1_Timer ()
If lblTime.Caption <> CStr(Time) Then
lblTime.Caption = Time
End If
End Sub
178
The procedure displays the system time by calling the intrinsic Time function. This
function returns a Variant containing the current time as a date/time value (VarType
7). When you assign it to a string variable or property, such as the Caption property
in this case, Visual Basic converts it to a string using the time format specified in the
Control Panel. If you want to display it using a different format, you can use the
Format function.
The Interval property for the timer is set to 500, following the rule of setting the
Interval to half of the shortest period you want to distinguish (one second in this
case). This may cause the timer code to update the label with the same time twice in
one second. This is wasteful and can cause some visible flicker, so the code tests to
—88
—89