100% found this document useful (1 vote)
860 views

Visual Basic Programmers Guide 1991

Visual Basic Programmers Guide 1991
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
860 views

Visual Basic Programmers Guide 1991

Visual Basic Programmers Guide 1991
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 470

Programmer's Guide

Programming System for Windows ™

Microsoft Corporation
Information in this document is subject to change without notice and <loes not represent a commitment
on the part of Microsoft Corporation. The software described in this document is furnished under a
license agreement or nondisclosure agreement. The software may be used or copied only in accordance
with the terms of the agreement. It is against the law to copy the software on any medium except as
specifically allowed in the license or nondisclosure agreement. No part of this manual may be
reproduced or transmitted in any form or by any means, electronic or mechanical, including
photocopying and recording, for any purpose without the express written permission of Microsoft
CofP-pration.

© 1991 Microsoft Corporation. Ali rights reserved .


Portions of this product were developed for Microsoft by Cooper Software, inc.

Except as otherwise noted, compariies, names, and data used in examples, sample output, and screen
shots are fictitious and are used solely to illustrate potential uses of this Microsoft product.

Microsoft, MS, MS-DOS , the Microsoft logo, PowerPoint, CodeYiew, and GW-BASIC are registered
trademarks and Microsoft QuickBasic, Visual Basic, and Windows are trademarks of Microsoft
Corporati on. OS/2 and Operating System/2 are reg istered trade marks and Presentation M anage r is a
trademark licensed to Microsoft Corporation .
IBM and PS/2 are registered trademarks of International Business Machines Corporation .

Microsoft documentation uses the term "OS/2" to refer to the OS/2 systems - Microsoft& Operating
System/2@(MS@OS/2@) and IBM@OS/2®. The term "DOS" refers to the Microsoft@MS -DOS@and
IBM@Personal Computer DOS operating systems. The name of a specific operating system is used
when it is necessary to note features that are uniqu e to that system .

Thi s manu al was produced using Microsoft Word.

Doc umc nt I umber DB 129 7--1 -04 1 1

Print cct in l rcland : en


MicrosoftVisual Basic..

. Mi cro s oft Vi sun l Ba s te d es 1 ni


f il e !; d,t (; od e 8 un 't{,ndow t!e lp - --
1 as k H ame

ADDTASK.FR M
jButl o nH~w j! j P1oc: jc1,ck
• [xec ut ed t,h e never ""Hpw•· bu t ton is c li c ked

S ub Outto nHr1>1_ C J i ck ( )
Di fll l as k As l a s k l y p e. HeuHame As St d ng
HP"1Ha r.ie - 1 as k HaJne . r e x l

· S hot-J ano l1 1e 1· 1 o n 11
St- l ec t Ca s l' r 1· i o ri ty
Ca se H I Cll
H i Pt· i o,· i ' y - S h o,,,
Case ll[0 I Ul-1
1-IPdP d o t"i ty. Shou
Ca s r L Oll "'"'"''
•. ~· A• ,oon a s po u 1blc • l li!Jt,

-~ Oate · !-t ed,um


-r~,d~ ~u sl 1~ [IJ 1
,._ ~' ,t J , ... { • : ~• • • :•. ••• • ,,.. ~ ~ •,._-• ', 1 -'1'••, ·1 ,,.rff-' ~- •lo' ,'}~~ ~-,TT .. ~~ •~ . , ,~Mf ~ .~..l ~ "" ,., ~- -;-. -;:-• •-~~

t.

. ~

Contents

Document Conventions x111

Part 1 Getting Started


Chapter 1 What Is Visual Basic? 3
What You Should Know F irst 4
Vi sual Bas ic and Its Environme nt 4
M eeting the Challe nge o f Graphi cal A ppl ications 6
Wh at Can You Crea te? 9
The Vi sual Basic Doc um e nta ti o n Set I O
Wh at to Do Next 1 1

Chapter 2 Setup 13
Befare You Run Setup 14
Running Setup 15
Starting Visual Bas ic 17
Setting Up Your Printer 18

Chapter 3 Using the Tutorial 19


Wh at's in the Tutori al 20
Using the Tutorial 20

Chapter 4 Using Help 23


Wh at's in Help 24
Gettin g Help 24
Leaming to U se Help 28
Running Code Exampl es fro m He lp 29

Part 2 Visual Basic Essentials


Chapter 5 Overview of Visual Basic Development 35
Your Firs t Applicati on 36
Workin g with Proj ec ts 43
Saving Yo ur Work 45

Microsoft Visua l Basic Programm er's Guide


rv Contents

Chapter 6 Drawing the Interface 47


Drawing Controls 48
Resizing , Moving , and Del eting Controls 53
Saving the Investment Calculator 55

Chapter 7 Setting Properties 57


The Role of Properties in Vi sual Basic 58
Using the Properties Bar 58
Setting Properties for the ln vestment Calcul ator 6 1
Other Ways to Set Properti es 64

Chapter 8 Attaching Code 65


When Do You eed Code') 66
Writing Event Procedure s 67
How the Code Works 74
Creating an Executablc Fil e 76

Part 3 Application-Building Techniques


Chapter 9 Language Elements 79
Microsoft QuickBasic and Visua l Basic 80
Sorne Mechanics (Commcnt s. umbers, Stateme nts) 80
Setting and Retrievi ng Properti es and Storing Data 8 1
Vi sual Basic Variables 82
Scope of Variables 84
Control Structures 86
Sub and Function Proccdurcs 93
Vi sual Basic Operators 98

Chapter 10 Responding to Commands 101


Responding to Command Bu tt ons 102
Controlling Command Button s at Run Time 107
Crcat ing a Men u-Dri ven Arr li ca ti on 109
Contro lling Menu s at Run T ime 1 13
Add in g and Deleting Menu Co mmands 11 6
Shortcut and Access Keys 120
Co ntrollin g the Tab Order 12 1

Microsoft Visual Basic Progra mmer's Guide


Contents v

Chapter 11 Getting lnformation from the User 123


Advanced U se of Text Boxes 124
Providing Choices with Option Buttons 129
Using Check Boxes 132
Providing Choices with List and Combo Boxes 134
Getti ng Inp ut with Scroll Bars 140
Prompting for Input with InputBox$ 143

Chapter 12 Displaying and Printing lnformation 145


Displaying Temporary Information with MsgBox 146
Using Labels to Display Output 147
Setting Charac teristics of Text (Fonts) 149
Printing to Form s and Picture Boxes 151
Printing Tabul ar Data 154
Formattin g Numbers, Dates, and Times 156
Send ing Output to the Printer 158

Chapter 13 Creating Graphical Effects 161


Adding Pictures to Your Forms 162
Moving Control s Dynamically 166
Resizing Controls Dynamicall y 168
Showing and Hiding Controls 168
Adding and Removing Controls 169
Sett ing an Object ' s Coordinate System 17 l
The Fundamental s of Drawing 175
Drawing Lines and Shapes 182

Chapter 14 Responding to Mouse Events 195


Mouse Events 196
Positi oning a Control with the Mouse 197
Graphical Mouse Application s 198
The Button and Shift Arguments 202
Draggin g and Dropping 207 ;=--

Chapter 15 Creating Multiple-Form Applications 215


Methods and Statements that Handle Forms 2 16
Setti ng Form Properties 217
Designatin g a Startup Form or Module 220
Ch oos ing An lean 221

Microsoft Visual Basic Programmer's Guide


v1 Conte nts

Load in g and Displ ay ing Forms 222


Hiding Forms 224
Unl oad in g Forms 226
Exi ting a Multipl e-Form Appl ication 226

Chapter 16 Dt;!bugging 227


Approac hes to Debugging 228
Design T ime, Run Time, and Break Mode 229
Halting Exec uti on at a Problem Statement 230
Run ning Selected Portions of Yo ur Appl ication 233
Testing Data and Procedu res in the Immediate Window 235
Special Considerati ons in Debugging Events 239
Testing and Us ing Co mmand-Line Arguments 240

Part 4 Advanced Applications


Chapter 17 Advanced Language Features 243
Cont ro lling Exec uti on 244
Data Dec lara tion 247
Array s 252
The Globa l Modul e 257
Ty pe and Constant De finiti ons 258

Chapter 18 lnteracting with the Environment 263


Workin g wi th Se lec ted Text 264
Us ing the Clipboard Object 265
si ng Time r Controls 268
Writing !die Loops with DoEvents 273
Writ ing Low-Leve l Keyboard Handl ers 275

Chapter 19 Handling Run-Time Errors 279


Why se Erro r Handling? 280
How to Hand le Erro rs 282
Unanticipated Errors 286
Cen tra lized Error Handling 288
Dc laycd Erro r Handli ng 292
Turn in g Off Error Handli ng 293

Microsoft Visual Basic Programmer's Guide


Contents vii

Chapter 20 Using the File-System Controls 295


Examining the File System 296
The Launch Pad Application 298
A File + Open Dialog Box 305
Other Ways of Using File-System Control s 314

Chapter 21 Processing Files 315


Working with Data Files 316
Using Sequential Access for Text Files 320
Records in Random-Access Files 331
Binary File VO 350

Chapter 22 Communicating with Other Applications 353


What Is Dynamic Data Exchange? 354
Creating Links At Design Time 356
Link Properties 358
Link Events 362
Enabling Users to Create Their Own Hot Links 365
U sing Methods to Perform DDE Operati ons 369
Handling Errors 372
Sending Key strokes to Other Applicati ons 375

Chapter 23 Extending Visual Basic 377


Loading Custom Controls 378
Declaring and Calling DLL Routines 379
Special Con siderations When Declarin g DLL Ro utin es 380
Calling DLL Routines with Specific Data T ypes 382

Part 5 Appendixes
Appendix A Adapting Basic Code 391
Importing Bas ic Files 392
Program Structure 392
Scope of Variables 394
Event and Error Handling 395
Input and Output 395
Language Mec hanics 396
Unsupported Key word s 396
Keywords with Specifi c Differences 397

Microsoft Visua l Basic Programmer's Guide


viii Contents

Appendix B lcon Library 399


Arrows and Pointers 400
Communication 401
Computers 402
Flags 403
Mail 404
Miscellaneous 404
Office 406
Traffic Signs 408
Writing 408

Appendix C Glossary 411

lndex 423

Microsoft Visual Basic Programmer's Guide


¡{-.h.. . ,,: . ... .. . ·~ '<"' • •. • •• '. •• · . ·"/. _-•, . ;~ , •; ,'f_t •it•:•• ·- ,. :•~ . ,., , '· •• ••. , ,'•' • .,, . º~~~ .,,•" ..¡ ·•:•,..~

~ ~

Figures and Tables

Figures
Figure 1.1 The Vi sual Basic Interface 6
Figure 1.2 How objects respond to events 7
Figure 1.3 Sorne of the properti es of a text box, with corresponding settings 8
Figure 1.4 A sampling of applications you can create with Visual Basic 9
Figure 2.1 Quitting Setup 16
Figure 3.1 The Help Menu 20
Figure 3.2 The Main Menu 2 1
Figure 3.3 Buttons in T utorial lessons enable you to navigate or see where
you are. 22
Figure 3.4 The Opti ons Menu 22
Figure 4 .1 Using F l to get Help 25
Figure 4.2 Search Di alog Box 26
Figure 4.3 A jump in Help 27
Figure 4.4 Definiti on Window 27
Figure 4.5 Index in Using Windows Help 28
Figure 4.6 Click the jump to go to acode example. 29
Figure 4.7 The Forrn_Click procedure with LineDemo entered 30
Figure 4.8 An exarnple with code that goes in the global module 3 1
Figure 5.1 The Project Window 36
Figure 5.2 Text box and command button tools in the Toolbox 37
F igure 5.3 Text box and command button controls on a form 38
Fi gure 5.4 The Pro perti es Bar 38
Figure 5.5 The Properti es bar with Ct!Name property set to Readout 39
Figure 5.6 The Code window wi th code for the Readout text box 39
Figure 5.7 The Code window with the Click procedure di splayed, and with a li st
of other eve nts 4 1
Figure 5.8 The Code window with the completed HelloButton_Click
procedu re 42 ~
Figure 6.1 The Toolbox 48
Figure 6.2 The Completed ln vestm ent Calcul ator 49
Figure 6.3 Contro ls with default names 50
Figure 6.4 Text box too! selected in the Toolbox 50
Figure 6.S Draw ing th e text box S 1
Figure 6.6 The !abe! and co mmand button too ls in th e Toolbox 5 l

Microsoft Visu al Basic Programm er's Guide


X Figures and Tables

Figure 6.7 A selected tex t box displays sizing handles. 53


Figure 6.8 Multiple-selected controls are outlined with gray sizing handles. 54
Figure 7.1 The Properties Bar 59
Figure 7.2 The Settings box displays a list of possible settings for the
selec ted property , 60
Figure 7.3 The ln vestment Calculator before and after properties are set 62
Figure 7.4 Property settings for size and position 64
Figure 8. 1 The co mpleted Investment Calculator 66
Figure 8.2 Selecting an object in the Code window 69
Figure 8.3 Selecting the CalcCmd_Click procedure 70
Figure 8.4 Event procedure in the Code window 72
Figure 9.1 Variable levels, from local to global 84
Figure 9.2 How general procedures are called by event procedures 93
Figure 10.1 Command button with caption 102
Figure 10.2 Picture box with icon from the Icon Library 103
Fig ure 10.3 An application with two command buttons 104
Figure 10.4 A shell application 106
Figure 10.5 Action and Info Menus 109
Figure 10.6 Menu Design window for the Try Menus application 110
Figure 10.7 A menu command with a check mark 114
Figure 10.8 The Window menu of the Program Manager 116
Figure 10.9 A Co ntrol Array 116
Figure 10.10 Application Manager 117
Figure 11 .1 Validation Example 125
Figure 11 .2 Us ing option buttons to give the user a choice 129
Figure 11.3 Choos ing a number sys tem with option buttons 130
Figure 11 .4 Check Box Example 132
Fi gure 11 .5 When this check box is selected, letters are entered as uppercase 132
Figure 11 .6 A li st box 134
Figure 11.7 A combo box wi th list closed and with list opened, and a drop-down
li st box 134
Figure 11 .8 The Population s List Box 136
Fig ure 11 .9 A Ji st box , command button, and text bóx that work together 138
Figure 11 . 10 Scroll bars in th e Windows Control Panel 140
Fig ure 11.1 1 Horizo ntal and vert ical scroll bar controls in Visual Basic 140
Fi gure 11.12 Using scroll bars to control color 142
Fig ure 11.1 3 A dialog box created with InputBox$ 144
Figure J 2. 1 MsgBox Example 146
Fig ure 12.2 Temperature Co nverter 147
Figure 12.3 Us ing built-in print zones 154
Figure 12.4 Using tabs in a tabl e 155

Microsoft Visual Basic Programmer's Guide


Figures and Tab les xi

Figure 13.1 Samples from the Visual Basic Icon Library 164
Figure 13 .2 Icons MAIL16A.ICO and MAIL16B.ICO from the Icon Library 165
Figure 13.3 Left and Top properties 166
Figure 13.4 A button that moves when clicked 167
Figure 13.5 A control array of three command buttons 169
Figure 13.6 Scale running from (100,100) to (200,200f- 173
Figure 13 .7 Scale with negative ScaleHeight setting 173
Figure 13.8 Byte layout of color values 180
Figure 13 .9 A line drawn with the Line method 182
Figure 13.10 A spoked pattern 183
Figure 13 .11 Lines of varying width 184
Figure 13.12 Lines drawn with different settings of the DrawStyle property 185
Figure 13.13 Comparing the color value 187
Figure 13 .14 Filling a box with a salid pattern l 89
Figure 13 .15 Ellipses drawn with the Circle method 19 1
Figure 13.16 How angles are measured for a circle 192
Figure 13.17 Using the Circle method to draw ares 193
Figure 13.18 Using negative arguments to connect an are to its center 194
Figure 13.19 Effect of reversing arguments 194
Figure 14.1 Moving a control to the location of the mouse pointer 197
Figure 14.2 The Cli ck-A-Li ne application draws lines wi th the Line method 198
Figure 14.3 The Scribble Application 199
Figure 14.4 A demonstration of where MouseMove events occur 200
Figure 14.5 How bits represent the state of the mouse 202
Figure 14.6 How bits represent the state of the SHIFf, CTRL, and ALT keys 206
Figure 14.7 Dragging a control at run time 207
Figure 15.1 The Beatles Form 217
Figure 15.2 The GroupChoice form is a dialog box. 2 19
Figure 15.3 The Welcome form is th e startup form . 220
Figure 15.4 Visual Basic standard icon and the icon for the We lcome form 221
Figure 15 .5 The GroupChoice Form 223
Figure 16.1 Run-time errors such as "Type mismatch" halt executi on. 23 1
Figure 16.2 A procedure halted by a breakpoint 232 _
Figure 16.3 The Immediate W indow 236
Figure 16.4 Using a question mark to print to the Immediate window 236
Figure 18.1 Moving data to and from the Clipboard wi th SetText and GetText 265
Figure l 8.2 A timer control 268
Figure 18 .3 The Digi tal Clock Application 270
Fi gure 19. 1 Program flow with Resume and Resume Nex t 284
Figure 20. 1 The tool s for the file-system contro ls 296

Microsoft Visual Basic Progra mmer's Guide


xii Figures and Tables

Figure 20.2 The file-system controls in action 296


Figure 20.3 The Launch Pad Application 299
Figure 20.4 The Filelnfo Dialog Box 305
Figure 21.1 The Text Editor Application 321
Figure 21.2 How records appear in a random-access file 331
Figure 21.3 The Record Editor Application 336
Figure 21.4 Adding a horizontal scroll bar to Record Editor 349

Tables
Table 2.1 Command-Line Options 17
Table 9.1 Standard Variable Types 83
Table 9.2 Vi sual Basic Operators 98
Table 22.1 DDE Statements in Microsoft Excel, Word, and Visual Basic 372

Microsoft Visual Basic Programmer's Guide


.,'-:·•·•'. . . . . ·., ,,. : '···.,--,._.a:-.-; __.,,~t .,;, . :_ '."'f ,. -/- •,: .. , -'· , . ~ :.:~ - , .•.. : ,._... ,. ,,~L ., -. . .' . .,
. .
f '

Document Conventions

This manual uses the following typographic conventions. _


Example of convention '
Description
Sub, If, ChDir, Print, Time$ Words in bold with initial letter capitalized
indicate language-specific keywords with
special meaning to Visual Basic.
BackColor, Click, Debug object N ames of properties, events, and special
objects appear with initial letter capitalized.
setup Words you're instructed to type appear in
bold.
event-driven In text, italic letters are used for defined
terms, usually the first time they occur in the
book. Italics also are used occasionally for
emphasis.
eventname In syntax , italic letters indicate placeholders
for information you supply.
[expressionlist] In syntax, items inside square brackets are
optional.
{While IUntil} In syntax, braces and a vertical bar indicate a
mandatory choice between two or more
items. You must choose one of the items
unless ali of the items also are enclosed in
square brackets.
Synta x error This font is used for variables and error
messages.
Sub HelloB utt on_ Click () This font is used for code .
Rea dout. Text = "Hell o. worl d ! "
End Sub

Readout. Text = "Thi s shoul d a 11 be The line-continuation character ( • )


• on one 1 i ne in t he Code wi ndow." indicates that-code continued from one Iine
to the next in the book should be typed ali
on one line in the Code window .
CONST ANT.TXT Words in ali capital Ietters indicate
filenames .

Microsoft Visual Basic Programmer's Guide


xiv Docum ent Conv entio ns

E T ER Small capital letters are used for the names


of keys and key sequences, such as ENTER
and CTRL+R. (Key names in online Help
have only the initial letter capitalized.) The
key names correspond to the names on the
IBM Personal Computer keyboard. Other
machines may use different names.
ALT+FI A plus sign (+) between key names indicates
a combination of keys . For example, ALT +Fl
meaos to hold down the ALT key while
pressing the Fl key.
DOWN ARROW Individual direction keys are referred to by
the direction of the arrow on the key top
(Left, Right, Up, or Down). The phrase
"arrow keys" is used whe n describing the
keys collectively.
HOME Other navi gational keys are referred to by
their specific names.
Graphical User Interface (GUI) Acronyms are usually spelled out the first
time they are used.

ma These icons are used to mark refere nces to


information in the online Help and Tutoría!.

Note M icrosoft documentation uses the term "OS/2" to refer to the OS/2 systems -
Microsoft® Operating System/2~ (MS@OS-/2@) and IBM@OS/2@. The term "DOS " refers to
the M icrosoft® MS -DOS ~ and IBM@Personal Computer DOS operating sys tems. The name
of a spec ific operatin g sys tern is used when it is necessary to note features that are un.ique to
that syste rn .

Microsoft Visual Basic Programmer's Guide


Document Conventions X\

Programming Style in This Manual


The following guidelines are used in writing programs in this manual. For more information .
see Chapter 9, "Language Elements."
• Keywords appear with initial letters capitalized, while constants appear in all capital
letters: ~

' Sub , If, ChDir , Print , Ti me$ are keywords.


Print "Title Page "

' TRUE and FALSE are constants


' equal to -1 and O, respectively.
Global Const TRUE = -1
Global Const FALSE= O

• Variable names are lowercase with an initial capital letter. Variable names with more
than one syll able may contain other capital letters :
Gov As String * 30
PerCapincome As Double

• Line labels are used instead of line numbers. The use of line labels is restricted to error-
handling routines :
OpenError
If Err = 71 Then
Print Error$
Resume
Else
End
End If

• An apostrophe ( ') introduces comments:


This is a comment ; these two lines
' are ignored when the program is running .

• Control-flow blocks and statements in Sub and Function procedures are indented from
the enclosing code:
Sub Commandl_Click
If X > O Then
Textl.Text = " X is greater than O."
End If
End Sub

Microsoft Visua l Basic Programmer's Guide


xv1 Document Conventions

• As noted earlier, lines too long to fit on one line in this manual may be continued on the
next line using a line-continuation character ( • ).
Sub Form_MouseDown (Button As Integer , Shift As Integer , X As Single,
• Y As Single)

Microsoft Visual Ba sic Programmer's Guide


Part 1 begins your exploration of Visual Basic. It introduces y ·
Visual Basic is all about, explains how to use the documenta n t, and
helps you get Visual Basic installed on your computer. Afte ea ng Part l .
you'll want to run the online Tutorial and read Part 2, "Vi al
Essentials," to see what Visual Basic can do.
What Is Visual Basic?

Welcome to the graphical user interface (GUI) revolution . If you want to create applications
for Microsoft Windows or OS/2 Presentation Manager, Visual Basic is the product for you.
Visual Basic is a development system especially geared toward creating graphical
applicati ons. It includes graphical design tools and a simplified, high-level language. It
emphas izes feedback and debugging tools that quickly take you from an idea to a running
applicati on.

.!--~~-
-- ----~---
--_..
Visual Bas ic is centered around two types of obj ects: You create windows, called forms, and
on those forms you draw other objects, called controls. Then yo u program how form s and
controls respond to user actions. The applicati ons you produce are fas t and can include all of
the most common features users expect in a GUI environment.
This chapter gives you an overview of Visual Basic and suggests th e best ways to use the
doc umentation set. The main sections in this chapter are:
• What You Should Know First
• Visual Basic and Its Environment
• Meeting the Challenge of Graphical Applicati ons
• What Can Yo u Create?
• The Visual Basic Documentation Set
• What to Do Next


4 Part 1 Getting Started

What Vou Should Know First


Before you begin using the Visual Basic documentation set (this manual, the Language
Reference , the online Tutorial, and online Help), you need to understand the fundamentals of
using Windows or Presentation Manager. The documentation assumes you know how to use
a mouse, open a menu, and select options. lf you need to review these techniques, consult
the documentation that comes with Windows or Presentation Manager.
You also should have sorne understanding of programming. No extensive experience or
specific language knowledge is required, but you '11 probably find this manual easier to
follow if you already know how to use loops, lf... Then ... Else statements, and variables.

Note If you're experienced with Microsoft QuickBasic, you'll learn Visual Basic all the
faster. However, you can transfer QuickBasic code to Visual Basic only after making certain
changes. (In sorne cases, large amounts of code can be transferred almost directly, but user
interface code must be rewritten.) See Appendix A, "Adapting Basic Code."

Visual Basic and lts Environment


You may find that Visual Basic is unlike any programming too! or application you've ever
used. To understand Visual Basic, first consider the world in which it works.

The Graphical User Interface


The Windows and Presentation Manager operating environments differ from DOS in at least
two important ways:
• Applications share screen space. A Visual Basic application runs in a group of one or
more windows and rarely takes over the whole screen.
• Applications share computing time . An application cannot run continually, or if it doe s. it
has to be able to run in the background .

The event-driven approach used by Visual Basic enables you to share computing time and
other resources (such as the Clipboard). An event-driven application consists of objects that
wait for a particular event to happen. (An event is an action recognized by a Visual Basic
object. Objects include forms and controls.)
Your Visual Basic code doesn ' t work in the linear fashion of a DOS program- starting at
the top, proceeding toward the bottom, and finally stopping. Instead, in event-driven
programming, you use code that remains idle until called upon to respond to specific user-
caused or system-caused events.
For example, you might program a command button to respond to a mouse click. When the
command button recognizes that the event has occurred, it invokes the code you wrote for
that event.

Microsoft Visual Basic Programmer's Guide


Chapter 1 What Is Visua l Basic?

While your application is waiting for an event, it remains in the environment (unless the use ,
closes the application). In the meantime, the user can run other applications, resize window s
or customize system settings such as color. But your code is always present, ready to be
activated when the user retums to your application.

Features Supported
Visual Basic enables you to take fu]] advantage of~raphical environments and operating
systems. With it you can create:
• A fu]] set of the objects you need to create Windows applications, including: command
buttons, option buttons, check boxes, list boxes, combo boxes, text boxes, scroll bars,
frames, file and directory selection boxes, and menu bars .
• Multiple windows in an application.

Visual Basic also offers:


• Highly flexible response to mouse and keyboard events at run time, including automated
drag-and-drop support.
• Ability to show and hide any number of items at run time.
• Direct access to the environment's Clipboard and to the printer.
• Direct system calls to Windows and Presentation Manager functions .
• Communication with other Windows or Presentation Manager applications through
dynamic data exchange (DDE), and extensibility via dynamic-link libraries. For example.
a user can call dynamic-link libraries (including Windows functions) from within Visual
Basic code.

In addition, Visual Basic adds a number of specific programming features, which you'll
leam more about later in this manual :
• Graphics statements.
• A powerful math an d string-handling library.
• Easy-to-use string variables .
• Both fixed arrays and dynamic arrays. (The latter help to simplify memory-management
problems .)
• Random-access and sequential file support.
• Sophisticated run -time error handling.
~

Visual Basic also makes development easier by providing a set of powerful debugging
commands that help you isolate and correct errors in your code. Visual Basic operates as an
interpreter, instantly translatin g your statements into "runnable" form as soon as you type
them. But once you 've completed your app lication , you can convert it into an executable file
that is relatively small and fast and can run outside the Visual Basic environment.
The Visual Basic package also includes an Icon Library. The library consists of icons that
you can use to add visual appeal and functionality to your applications .

Microsoft Visual Basic Programmer's Guide


6 Part 1 Getting Started

Meeting the Challenge of Graphical Applications


GUI environments generally make computing easier - and more fun-for the user. But
these environments create new challenges for developers, who now must think visually,
write code that responds to events, and anticipate how users will interact with applications.
VisuaJ. Basic helps you think visually because it enables you to draw objects just as you want
them to appear to your users.
The objects you can create include:
• Forms: windows that you customize.
• Controls: graphi cal objects drawn on a form , including text boxes, command buttons,
picture boxes, scroll bars, directory and file controls, and timer controls .
Timer control s are count-down or alarm-clock mechanisms that you draw like other
controls, but whi ch are alw ays hidden when an application is run. You can program a
timer to take ac ti on ata particular time._

Figure 1.1 shows th e Vi sual Basic interface. You ' ll leam more about the various parts of the
interface in Chapter 5, "Overview of Visual Basic Development."

Form Properties bar

=I Microsoft Visual Ba s ic (design] 1·1·


Eile .!;_dit .(;_ode Bun '.r!'indow .t!e lp
lcaption W l x l ✓ I orm1 li! I lt : 1020.1 1 55 1 ¾17 72Ll5 x Ll5Ll5

...
=I Fo rml 1· 1·11
~ ~ ..
A [M 3llllmllllE
oo =I Fo rm1
1 View Form 11
¡i¡¡j Global.has
Vi ew Code

Global
1
~ ® Object: lro,m 1~ Proc: j Click •-~ ·"'•""'
~. ~. Sub Fonn_ Cli c k ()
~ fil 1
End Sub
o El
EJ ~

t.11
+I 1 l +I 11

Toolbox Code window Pro ·ect window


Figure 1.1 The Visual Basic Interface

Microsoft Visual Basic Programmer's Guide


Chapter 1 What Is Visual Basic? 7

Understanding Event-Driven Programs


For each type of object you create, Visual Basic predefines a set of events that you can
respond to by writing code. It's easy to respond to events: Forms and controls have the built -
in ability to recognize user actions and invoke the code associated with them.
You don't have to write code for all events. When you do want an object to respond toan
event, you write code called an event procedure -fprocedure that Visual Basic invokes in
response to an event. The procedure is named according to this convention:
objectname_eventname

The name itself establishes the association between the procedure and the event. When your
application is running, Visual Basic automatically invokes the appropriate procedure each
time an event occurs.
Here's how a Visual Basic application works :
1. An action is recognized as an event by sorne form or control. The action can be caused
by the user (such as a mouse click or keystroke) or by the environment (such as a timer
event) .
2. If there is a corresponding event procedure, it gets executed.
3. The application waits for the next event.

Figure 1.2 demonstrates how objects in Visual Basic respond to events. For example, when
the user clicks the command button named Commandl , the command button recognizes thi s
action as the Click event. Visual Basic then executes the Commandl_Click procedure, if it
exists.

Visual Basic ca/Is


In response to this action: this procedure:

User chooses the button


(usual/y with a mouse click) .. . ~C_l_
ick_~I • Command l _ Cli ck

User tabs to the button ... GotFocus •


1 1 Commandl Command l _ GotFocu s

User presses a key while the


button is selected... KeyPress •
I Command 1_KeyPress

Eventname Visual Basic procedures


attached to Command1

Figure 1.2 How objects re spond to events

Microsoft Visual Basic Programmer's Guide


8 Part 1 Getting Started

The procedures you write to respond to events can perform calculations, get input, and
manipulate parts of the interface. In Visual Bas ic, you manipulate objects by changing the
values of properties.

The Role of Properties


A property is a charac teristic of an object. For each type of object, Visual Basic predefines a
set of properties that apply to the object.
For example , sorne of the properties of a text box are shown in Figure 1.3 . (The ful] set of
properties is actu all y mu ch larger.) Note that even the name of the text box itself is a
property, as are the con tents of the text box, which are specified by the Text property .

Text box "Readout" Property Setting


¿ Ct!Name
~ T e xt
"Readout"
"Abe"

Abcl 1 Height 400 twips


2000 twips
~ w;dili
ForeColo black
BackColo white

Figure 1.3 Sorne of the properties of a text box, with corresponding settings

Each property has a name and a setting. The setting is the value of the property ; for instance,
the setting of the Bac kColor property could be white. You can change the settin g of most
properties whi le yo u are building an application, and with code when the application is run.
Much of the magic of Visual Basic stems from the fact that when you change the value of a
property, Visual Basic responds ri ght away, doing whatever is necessary to graphicall y
reflect the change . For exa mple, changing the value of the Height property causes Visual
Basic to immediately resize th e object.

An Enhanced Basic Language


The Visual Basic lang uage uses the si mplified sy ntax of BASICA and GW-BASIC, and
supports nearly ali of their capabilities. But Visual Basic also enhances them in severa)
major ways:
• It uses the modern progra mmin g structure of QuickBasic , including elegant structures for
controllin g progra m flow . If you 've used C, Pascal, or so rn e other structured language,
you'll find Visual Basic co nvenient and natural to use, and capable of expressi ng
complex programmin g log ic.
• It 's built aro un d events - ac ti ons recognized by Visual Basic objects.
• It has many direc t " hooks" into the graphi cal environment and operating sys tem.

Microsoft Visual Basic Programmer's Guide


Chapter 1 What Is Visua l Basic? 9

Visual Basic supports the majority of statements and function s supported in other versions of
Basic. It also adds sorne new capabilities in the form of methods. A method is a Visual Bas ic
keyword that is similar to a function or statement, but which always acts on a particular
object. For each object, Visual Basic predefines a set of methods you can use.

What Can Vou Create?


Visual Basic elirninates many of the complexities associated with using the Windows or
Presentation Manager Software Development Kit (SDK), yet it retains most of the
flexibility. Although there are sorne things possible only with the SDK, Visual Basic
supports the most typical things you ' d want to use in a graphical application.
Figure 1.4 shows a sampling of very different (and useful ) applications created with Visual
Basic: Calculator, a standard simulation of a hand-held calculator; IconWorks, an
application you can use to view and edit icon files; Cardfil e, another standard Windows
application ; and Scribble, a simple drawing program. As yo u' Íl see in Chapter 14,
"Responding to Mouse Events," Scribble requires onl y one line of code.

la Cardfile - (untitled) DD
Eile .!;_dit '{iew ~ard .S.earch !::!elp •
Card View • • 1 Card

la lconWorks Editor: IUntitledl DD


e=== = = = = = = ==I file .!;_dit Qptions Iool s !con s .!;!rus h !::!e lp

[j]•
Spanish Rice

1/2 cup cbopped onion


1/2 cup cbopped green
2 cups instant rice
1 pound ba • burger (op
1 can (16 oz_) to • ato ••
3- -drop s bot sauce
1 cup •ater
••
Undo to:

M o use B uttons

• •
Lelt Righl

~=¡==¡=¡==¡===¡==¡==='j ®

- ~ -....~ - -............¡ 1 . 961


;:- 0 00 [QE]
0 0 Oill C:J •
u00 00
1 ° l u0 •
Figure 1.4 A sampling of applications you can ereate with Visual Basic

Microsoft Visual Basic Programmer 's Guide


10 Part 1 Getting Started

The Visual Basic Documentation Set


The Vi sual Bas ic package includes fo ur documentation tool s, each designed to help you
learn and use a parti cul ar as pect of the product:
• The online Tutorí a! provides a hands-on introduction to the Visual B asic environment
and sorne fundam enta l Vi sual B asic concepts. You should start with the Tutorial. It is
fas t-paced, and its m odul ar structure enables you to leam in sm all segments.
• Thi s manual, Programmer's Cuide, concentrates on working with the Vi sual Basic
language . It ex plains programming techniques and uses frequent examples to show how
those techniques work in ac tu al applicati ons. After running the Tutorial, you will
probabl y want to read this manu al fo r di scussion of how and why the code works.
• The Language Reference summarizes the Visual Basic language by programming tasks
and li sts the methods, properties, and events that apply to each obj ect. It al so includes a
detailed A- Z reference fo r fu nctions, statem ents, m ethods, properties, events and o bjec ts.
(The sa me reference info rmati on is in online Help.) In addition , the Language Reference
contain s an ANS I chart and a table of trappable error m essages.
• Th e Help sys tem is a ready reference to the Visual Basic interface and to Vi sual B asic
language statements. Once you have a sol id understanding of Vi sual B asic fundamentals,
refer to Help for a me mory refresher orto learn about sorne advanced techniques. The
Vi sual Basic language topics in Help include substantial code exampl es th at you can
copy and paste directly into your own applications.

Cha pters 3 and 4 give more complete descriptions of the Tutori al and H elp.
T he fo ur parts of the doc umentati on se t are designed to complement one anoth er. To help
yo u qu ickl y find infor mati on in Help and the T utorí a!, thi s manu al includes a number of
cross- references . In the fo ll ow ing chapters, m ost of the cross-references are marked with
these icons:

m Search Help for:


controls a See Tutorial Lesson:
"Working with Visual Basic "

T he Help ico n represents the Fl key. You can press that key while running Vi sual B asic to
go to Help . T he word o n the second lin e is call ed a keyword. ("Keyword" in thi s case m eans
a search term ; lang uage keywords incJude fun ction s, state ments, operators, and method s.)

To search Help for a keyword:


1 In th e He lp window, press ALT +S o r just S.
2 Type th e keyword .
3 Press ENTER to carry o ut th e search.
T op ics assoc iated w ith the keyword are di splayed in the Topics Fo und li st box . Use the
arrow keys to se lec t the top ic yo u want.
4 Press ENTER to go to the se lected topic .

Microsoft Visual Basic Programmer's Guide


Chapter 1 What Is Visual Basic? 11

The text next to the Tutorial icon refers you to a specific lesson. To start the Tutori al, choosc
Tutorial from the Help menu in Visual Basic.
The index for this manual also includes cross-references to the Tutorial and to Help .
In addition to the documentation , the V isual Basic package comes with a set of sampl e
applications that you can load into Vi sual Basic . These ·applications are useful in the mselves.
but are also excellent leaming tool s. You can copy "1!Y part of them into your own
applications, modifying them as you need to.

How This Book Is Organized


This manual is organized around five parts, each with a distinct purpose :
• Part 1, "Getting Started," describes preliminary steps, including installation (th e Setup
program) and how to use the Tutorial and Help.
• Part 2, "V isual Basic Essenti als," describes the basics of drawing a Visual Basic inte rfac e
and attachin g code to it.
• Part 3, "Application-Building Tec hniques," explains the meth ods for writin g code to do
common tasks, including getting input, di splaying output, mouse events, and creatin g
graphical effec ts.
• Part 4, "Advanced Applicati ons," ex pl ai ns techniques used in substanti al appli cations,
including file handling, error hand ling, and DDE.
• Part 5, "Appendi xes," includes guidelines for adapting code written in other versions of
Microsoft Basic, di sc ussion and illu strations of the Icon Library , anda glossary of
technical terms.

What to Do Next
This chapter has introduced you to sorne ge neral Visual Basic concepts. To really get th e
feel of the product, you' ll need to build and run sorne applications .

lmportant If you have the product installed airead y and are anxious to build an application , turn to
Chapter 5, "Overv iew of Visual Basic Development," which leads yo u through a simple
application.

For the most thorough introduction to Visua l Basic:


1. Run the Tutorial. Work th rough the e ntire Tutorifü , or choose th e lessons and topics that
interest you the most.
2. Work throu gh Part 2 of thi s manu al, preferably at the computer, to understand some
fundamental s of Visua l Basic code and how it is used.
3. Read Part 3 to leam the most frequently used coding techni ques.
4. Refer to Help or th e Languag e Reference whil e you work.

Microsoft Visual Basic Programmer's Guide


12 Part 1 Getting Started

Alternatively, if you are fami liar with event-driven programming and with the Windows or
Presentation Manager environment, you might try a faster track:
1. After working through Chapter 5, start exploring Visual Basic, referring to Help or the
Language Reference when you need to.
2. Skim through the rest of Part 2, paying particularly close attention to Chapter 8,
"f.,.ttaching Code."
3. Read Part 3 to learn the most frequently used coding techniques.
4. Use the Tutorial for lessons on selected topics.

Microsoft Visual Basic Programmer's Guide


Setup

This chapter explains how to install Visual Basic on_your computer using the program
SETUP.EXE. Toe Setup program (which was writte1i in Visual Basic) creates new
directories and copies a number of files - Visual Basic itself, the Help system, the Tutoría! ,
sample applications, and the Icon Library - from the distribution disks to your hard disk.

lmportant You cannot simply copy files from the distribution disks to your hard disk and run Visual
Basic. You must use the Setup program to decompress and install the files.

nning Setup, yo u' 11 have a working version of Visual Basic on your


14 Part 1 Getting Started

Befare Vou Run Setup


You ' re probably eager to install Visual Basic immediately. But first, take a few minutes to
make sure your computer meets sorne minimum requirements and your Vi sual Basic
package is complete.

Check the Hardware and System Requirements


To run Visual Basic you must have certain hardware and software installed on your
computer. The requirements are different depending on whether you're running Visual Basic
for Windows or Vi sual Basic for Presentation Manager.

Visual Basic for Windows


Visual Basic for Windows run s in either standard or enhanced mode of Microsoft Windows
version 3.0 or hi gher. The bas ic requirements are:
• Any IBM-compatible machi ne built on the 80286 processor or higher.
• A hard disk.
• A mouse.
• A CGA, EGA , YGA , 85 14, Hercules, or compatible display. (EGA or hi gher resolution
is recommended.)
• MS-DOS version 3.1 or hi gher.
• Windows versio n 3. 0 or hi gher in standard or enhanced mode.
• One megabyte of rn e mory.

Visual Basic for Presentation Manager


Visual Basic for Prese ntation Manager req uires:
• Any IBM-compat ibl e machi ne built on the 80286 processor or hi gher.
• A hard di sk.
• A mouse.
• A CGA , EGA, YGA , 85 14, Hercul es, or compatible di splay. (EGA or hi gher resoluti on
is recommended.)
• OS/2 vers ion 1.2 or hi gher.
• Four mega bytes of memory .

Microsoft Visual Basic Programmer's Guide


Chapter2 Setup 15

Check the Visual Basic Package


These items should be in the Visual Basic package:
• Registration card: Please take time to fill out and mail this card. If you do, you'll be
notified of future software releases, and it will be easier to get customer assistance.
• Disks: The disk labels indicate how many disks sh.9uld be present; check to make sure al 1
the disks are there. The disk labeled Disk 1 contai!Th a text file named PACKING.LST
that lists the location and description of all disk files on the Microsoft Visual Basic disks .
• Programmer 's Guide: the book you're reading now. lt explains how to use Visual Basic.
• wnguage Reference: an alphabetic reference to Visual Basic language function s,
statements, and methods, in addition to all objects, events, and properties.

If any pieces are missing, contact the retailer from whom you bought Visual Basic.

Make Backup Copies of the Distribution Disks


Before you run Setup, back up the Visual Basic disks using the Copy or Diskcopy command
in DOS or OS/2. Or, use the Copy Diskette command on the Disk menu in the File Manager.

Read the README.TXT File


If there are corrections or additions to this book or the wnguage Reference, they 're listed in
a file called README.TXT. Toread the file, double-click the ReadMe icon in the File
Manager. Check the first section of README.TXT for corrected information on installing
Visual Basic.

Running Setup
When you run the Setup program (SETUP.EXE) to install Visual Basic on your computer,
you'll set a path for Visual Basic and then select which of the Visual Basic files you want to
install .
You can start Setup from Windows or Presentation Manager, or from DOS .

To start Setup from Windows or Presentation Manager:


1 Insert Disk l in drive A.
2 In the Fi le Manager, choose Run from the File men_µ.
;:--
3 Type a: setup
4 Follow the Setup instructions on the screen.

Microsoft Visual Basic Programmer's Guide


16 Part 1 Getting Started

To start Setup from DOS:


1 Insert Disk I in drive A.
2 Switch to that dri ve by typing a:
3 Type win setup
4 Follow th e Setup instructions on the screen.

Ouitting Setup
To quit Setup , click the Exit button in the lower right of the Setup screen, as shown in
Figure 2.1. This di splays a Yes/No message. Choosing Yes quits Setup; choosing No cancel s
your req uest to quit and retums you to the Setup program.

Microsoft Visual Basic Setup

Type your full name or the name of the company that


purchased Microsoft Visual Basic.

The name you type will be used by Setup for subseque·nt .


installations of Visual Basic and will appear in the
application itself.

Name :

Continue 1 Exit

Figure 2.1 Ouitting Setup

Changing Options After Ouitting Setup


To reinstall Visual Basic later in another directory or install other portions of Visual Basic,
run Setup again . You may run Setup as many times as you wish.

Microsoft Visual Basic Programmer's Guide


Chapter 2 Setup 17

Starting Visual Basic


You can start Visual Basic from Microsoft Windows or Presentation Manager, or from DOS.
Note that the following methods won' t work unl ess Visual Basic is in the path in your
AUTOEXEC.BAT file.

To start Visual Basic from W indows or Presentation Manager:


1 In the File Manager, choose Run from the File menu.
2 Type vb

To start Visual Basic from DOS:


• At the system prompt, type win vb

Using Command-Line Options


lnstead of starting Visual Basic in its default mode as described above, you can use
command-line options to control what Visual Basic does when you start it.

To use command-line options from Win dows or Presentation Manager:


1 In the File Manager, choose Run fro m the File menu .
2 Type vb [[/run] filename ] [/cmd commandline ]

To use command-line options from DOS:


• Type win vb [[lrun]filename ] [/cmd commandline]

Table 2.1 explains what each of the opti ons does.


Table 2.1 Command-Line Options
Command-line option Explanation
/RUN Run s the spec ifi ed proj ect in Vi sual Basic. (A
filename must be specifi ed.)
filename Loads the spec ifi ed file.
/CMD Allows you to use later everything typed after
/CMD (the comm and-line arg uments) .
...
For more information on using comm and-line options:

m Search Help for:


Command$

Microsoft Visual Basic Programmer's Guide


18 Part 1 Getting Started

Setting Up Vour Printer


Visual Basic prints to the printer that you set up in Windows or Presentation Manager. For
information on how to set up that printer, consult the documentation for Windows or
Presentation Manager.
To-print from Visual Basic, choose Print from the File menu.

Microsoft Visual Basic Programmer's Guide


Using the Tutorial

The online Tutorial gives you a quick understandin~of how Visual Basic works. It shows
yo u the Visual Basic interface and demonstrates techniques you'll use in building
app lications. One of the best ways to learn Visual Basic is to run the Tutorial first and the n
read this manual.
You run the Tutoría! from within Visual Basic, so it's easy to retum to it when you want to
learn more. You don ' t need to finish all of the lessons befare you start using Visual Basic.
lf you want to run the Tutorial right away, choose Tutorial from the Help menu. To learn
more about the Tutorial befare you run it, read thi s chapter. The section s in this chapter are :
• What's in the Tutorial
• Using the Tutoría!

••
20 Part 1 Getting Starte d

What' s in the Tutorial


The Tutorial has four lessons, as described in the following table. It's best to go through
them in the order shown , but that 's not required. The table gives you an estímate of the time
to complete each lesso n.
Time to
Lesson lnformation presented complete
"Introducing Visual Basic" Explains what Vi sual Basic is and what 20 minutes
kinds of applications you can create with it.
Shows you what a graphical user interface
is. Introduces you to the Visual Basic
development environment and shows you
how to use Help.
··working with Walks you through the process of creating a 30 minutes
Vi sual Basic" simple application in Vi sual Basic .
Introduces projects, forms, controls, events,
me nus, code, and debugging.
·'Creatin g Custom Demonstrates advanced design ideas suc h as 60 minutes
App lications" the use of graphics, color, and layout. Shows
you how to manage data stored in text fil es.
"Sample Applications" Demonstrates sorne of the sample 20 minutes
applications included with Visual Bas ic.

Using the Tutorial


To start the Tutori al, c hoose Tutorial from the Help menu , as shown in Fig ure 3. J.

lcaplion 1035. 11~0

tlbout...

Figure 3.1 The Help Menu

Microsoft Visual Basic Programmer's Guide


Chapter 3 Usin g the Tutorial 21

T he first scree n is the Menu , as shown in Figure 3.2. This is where you choose the lesson
yo u want to see. Noti ce th e buttons at the bottom of the scree n: Exi t and Instructions. To qui 1
the Tutoría! , click Ex it. To see in structions on how to use the Tutoría! , click Instructions.

- Visual Basic TutoñaJ - ~t1@~oft ~

Cl
Select a lesson o r c hoose ins huclions:

~ lntrodu c in g Vi sua l Bas ic

[ii] W o rk,ng with Visua l Bas ic

~ Creat,n g Custom Application s

[I]. Sampl e Appli cation s

Exil 1 1
lns huc tions 1

Ci,cK to ex,t Turorial. Click to see instructions on


how to use the Tu toría/.
Figure 3.2 The Mai n Menu

Each lesso n in the Tutorial includes severa! topics. Move through a topic by clicking the
Nex t button , or by pressing the SPACEBAR. To find out where yo u are in the lesson, click th e
icon in th e upper left of the screen, as shown in Figure 3.3 on the next page. The Tutoría!
d isplays a map th at shows you where you are in relation to other topics in the lesson.

Mic rosoft Visual Basic Programm er's Guide


22 Part 1 Getting Started

Click here to find out where


you are in the /esson.

_This tapie presents ttn overview of the Vi sual Btts ic


design environment. You'II learn about:

• Projects • Visual Basi c languttge


• Forms and co ntrol s • Menu bars
• Modules • Co lor palette

Eile [dil !;,ounlry

IIJ
Popula tion
cameroon
l 10.800.000
I
GNP S12.600.000.000
lncome pe , Capita ~I$_1_.1_67_ _ _ _~

Options Nexl

C/ick Next ar press the SPACEBAR


to see the next screen.
Figure 3.3 Buttons in Tutorial lessons e na ble you to navigate or see where you are .

Click Options to display the Options menu , as shown in Figure 3.4. Use the buttons on the
Options menu to move around within the Tutori al, orto retum to Visual Basic. You also can
get instructions on how to proceed durin g a lesson, or see a sllmmary of the current lesson.

Options

lnstructions Displays instructions on how to proceed.


Back Returns to the previous step.
~ ummary Jumps to the Summary far that lesson.
Menu Returns to the Menu.
Ex it Tutorial
Clases the Tutoría/ and returns to Visual Basic.

Cancel : Ese Clases the Options menu.

Figure 3.4 The 0ptions Menu

Microsoft Visual Basic Programmer's Guide


Using Help

Because it is an integral part of Visual Basic, online He!f> is installed automatically when
you run Setup. Help is the primary reference for the Visual Basic interface and one of two
prime sources of information on the Visual Basic language (the other being the Language
Reference manual). lt gives you instant reference information about properties, events, and
error messages, plus step-by-step instructions for each phase of building an application. Help
also includes reference on advanced tapies such as debugging and dynamic data exchange.
lt' s easy to keep Help handy as you work with Visual Basic, because you can move the Help
window where you want it and change its size to what suits you best.
For detailed information on Help, choose Using Help from the Help menu in Visual Basic,
or run the "Using Help" tapie in the first lesson of the Tutoría!.
The main sections in this chapter are:
• What's in Help
• Getting Help
• Learning to Use Help
• Running Code Examples from Help
24 Part 1 Getting Started

What' s in Help
Online Help is a comprchensive reference for nearly all aspects of Visual Basic. The
followin g table Ii sts the majar parts of Help. To start or switch to Help from Visual Basic,
press FI or choose Index from the Help menu, then choose one of the index entries.
Fo~_Help on From the Help index, choose
Essential steps in building an application Creating An Application
Visual Basic windows and tools Visual Basic Interface
Visual Basic menu commands and dialog Commands
box options
Conunon tasks in Visual Basic HowTo ...
Objects, properties, events, and methods Properties, Events & Methods
The Visual Basic programming language Programming Language
Useful key comb in ations Keyboard Guide
Using icons to enhance your applications Icon Library

There also is a part of Help called "Using Windows Help" that explains how to use Help
itself. For more information , see " Leaming to Use Help" later in this chapter.

Getting Help
In addition to using the index , there are four other ways to reach specific information in
Help .
When you're in Visual Basic:
• Selecta context-sensitive element of Visual Basic and press FI .

When you're in Help:


• Search for a spec ific keyword (either a earch term or language keyword) using the
Search command .
• Click a jump. A jump is an underlined word you can click to go to a topic related to th e
word.
• Click a word or phrase with a dotted underline to see its definition .

Microsoft Visual Basic Programmer's Guide


Chapter 4 Using Help 25

Context-Sensitive Help (F1)


Three parts of Visual Basic are context-sensitive, as shown in Figure 4. 1. "Context-
sensitive" means you can get help on these parts directly without having to go through the
Help menu. For example, you can get help on any word in the Visual Basic language by
placing the insertion point on or beside that word in th~Code window and pressing Fl.
....
... with the insertion = :.
File fdit Bookmark Help
' I•
. .,.
point on ar next
to a keyword ~
!ndex 1 \~;:ck
; '·, 1 Bfowse
•• 1 8'QWse
•• ~
1Sea.re
Press Fl to get Help =I Form Sub St atement .!
without having to go Object: 1Textl Acti on
Declares the narne. arguments. and code that
through the Help menu ... Subl Textl _ Change ()
form the body of a .S.\Ü! .RfQ~!t!:!~_r_e
End Sub Syntwc
[Static] Sub glob,rlntll71e [( ,,,g11mentns1 )]
[ st,rtementblod ]

., .,
[Exit Sub]
,,..,, •

... while in = .r•• .


'
:., · I·
anywindow File f dit Bookmark !jelp
9

=I Form
~
!ndex
1 \;,
¡}.':C.{.(
1 s,~,. 1 "~!,. 1 s~
~
11:

A @fil
Toolb ox
The Toolbox conto.ins a set of tools lhatyou
-

oo
---
can use to draw. move. or resize .GQfl.\r_o_l~ on
, Textl your fRrrn-You can choose thetoolyouwant
-~181 @ to use by clicking it.

- ffi . ~ • To open th e T oolbox. choose th e T oolbox


command from the Wí nd ow menu

-o El
[!El

-g -
To el ose the T oolbox, ch o ose the aose

., command from the C.0D)(Rl.m.~!!M-



....,,
~

= ; 1• ¡ . ,a- ' : · I·
Eil e f dit Bo okma rk !:le lp

...at an error
~
jndex 1 ·~ - I ,~\. 1 !!"' 1 Se~
message Out of memory •
1-

Error 7
=I Mi crosoft Vis

CD Ou t o f m e m o r .
More memor-¡ wa!> reqwred 1hon 1s evo.110.ble
Close ony opphc0.t1ons. docum ents. ar
source files the1a,e 1n memo,y but not
needed

E ..
• Cons,d e, break.mg the program mto multrple

.,modules
...
.,.,,

Figure 4.1 Using F1 to get Help

M icrosoft Visual Basic Programme r's Guide


26 Part 1 Getting Started

Press Fl from any context-sensitive part of Visual Basic to display information about that
part. The context-sensitive parts are:
• Words that are part of the Visual Basic language (statements, functions, properties,
methods, events, and so on)
• Error messages
• Every window in Visual Basic (Properties bar, Code window, dialog boxes, and so on)

Inside Help itself, you can press Fl to display the index to the Using Windows Help topics.

Searching Help
The quickest way to find a particular topic in Help is to use the Search command. Y ou can
use either the mouse or the keyboard to initiate the search; the latter is probably faster.

To search Help:
1 In the Help window, press ALT +S or just S to display the Search dialog box .
Help displays the Search dialog box, as shown in Figure 4.2.

Search
.S.earch For:

lri.m

absolute
access
access keys
access prope rties
activate

No T opics Found

Figure 4.2 Search Dialog Box

2 Type the first letter of the word or phrase you're looking for.
-or-
Select a word or phrase from the list of keywords.
When you type a letter in the Search For box, the selection in the list shifts to the first
keyword that starts with that letter. If several keywords start with the same letter, you can
type additional letters to move the selection to the keyword you want.

Microsoft Visual Basic Programmer's Guide


Chapter 4 Using Help 27

3 Press ENTER to carry out the search.


Topics associated with the keyword are displayed in the Topics Found list box. You can
use the arrow key s to change the selection in the list.
4 Press ENTER to go to the selected topic.

Jumps ....

The topics in Help are linked by jumps. Jumps are easy to spot because they are underlined
(and green on color monitors) , as shown in Figure 4.3. To see the topic related to ajump,
click the jump (or press TAB until the jump is highlighted, then press ENTER). Togo back to
the previous topic, click the Back button in the Help window, or press ALT+B (or just B).

lliJ .,\ ,: ••
!ndex i::r,·;:A $ ' ~ BrQwse
M~1oft

tJ,. Visual Basic Help


Steps to build an application.
Guide to windows and tools
Command s Reference to menu command s
and dialog boxes.
Ste p-by-step in structions •
+ ·

A 1ump to another tapie

Figure 4.3 A jump in Help

Definitions
Sorne of the words and phrases in Help are marked with a dotted underline (and are green on
color monitors). Help provides definition s for these terms. To see the definition , click the
underlined word or phrase and hold the mouse button down, as shown in Figure 4.4. Help
displays a definition window until you release the mouse.

Click a defined term in Help to see an explanation.

To view a defined term :


1 Po sition the pomte_r on the i:!.eft,:,_e_QJ!'!rm.
2 Pre ss the 1/ defin ed term ~
1 Oef1rnt1on s appear in a window like th1s
L
To learn more ebout Help, choose th1s tapie Getting
Ilnformation fr orn Cross-Relerences
Figure 4.4 Definition Window

Micro soft Visual Basic Programmer's Guide


28 Part 1 Gettin g Started

Learning to Use Help


Thi s chapter prov ides an overview of how to use Help. For more information, see "Using
Windows Help," the Help file supplied with Windows. To reach Using Windows Help:
• Choose Using Help from the Help menu in Visual Basic.
• Press F I from anywhere in Help.
• In Help itself, choose Using Help from the Help menu .

The Using Windows Help topics include complete information on Help basics, buttons,
commands, keys, and procedures, including navigating and searching. Figure 4.5 shows the
Using Windows Help index topic. When you use the Search command while in Using
Windows Help, the search does not include topics about Visual Basic - only information
about usi ng Help .

...._
Ei_le_ ~d~it_B_o_o_km._ar_k_t!~e_lP_ _~_
f; ___,. }- Help commands
1
,_.1....
~ _,ex__.'-__ _•._e ______,,_,. }- Help buttons
,tw
_,._,:_:.::_, ••_. .._B__
....._,. ____
lnd ex t o Usíng Help
11 you are new to Wmdows Help. choos e Help
Bas, cs
Usin g Help To pi cs
Help Bas,cs
Help Button s
Help Cornrnands
Help Kevs
Help Pro cedures
To choo s e a Help t opic:

~ •

Figure 4.5 lndex in Using Windows Help

C lic k the lndex button to retum to Visual Basic Hel p.

Microsoft Visu al Basic Programme r's Guide


Chapter 4 Using Help 29

Running Code Examples from Help


Many of the language topics in Help contain code examples. You can run these examples
from the Code window or from the lmmediate window. Both ways are described below
using the example code from the Line method topic. A special case involving the global
module is explained at the end of this section.
To run a code example, first copy the example into the.Code window. Then run it from the
Code window or from the Immediate window, as explained later in this section.

To copy a code example from Help to the Code window:


1 Create a new form by choosing New Form from the File menu, or use an existing form .
(For more information on creating and using forms, see the section on building the
"Hello, World!" application in Chapter 5, "Overview of Visual Basic Development. ")
2 Press Fl to open Help or switch to it.
3 In Help, search for "line," and go to the topic called "Line Method." Then page down to
the Exarnple heading and click the jump to the example for the Line method, as shown in
Figure 4.6.

Eile _E dil Bookmark ):!elp

Pro p erty. FillColor _Property. FillStyle


Prope rty. F ore Color Property. Color
Quick Reference RGB OBColor
Exe.mpl e
The exe.m le uses the Line method to dre.w
concentnc xes on e. form . To try th1s
example, p te the code into the
Declarat1on sectio n of e. forrn . Ce.11

Jump to example code

Figure 4.6 Click the jump to go to a code example.

4 Choose Copy from the Edit menu in Help to copy the entire example, or press CTRL+INS .
5 Exit or minimize Help.
6 Double-click the form to show the Code window.
7 In the Object box, select "(general)."
8 Choose Paste from the Edit menu to paste the example into the Code window, or press
S HI FT+ INS,

Note that the name of the procedure -LineDemo --,-fo!Jows the word "Sub."

Microsoft Visual Basic Programmer's Guide


30 Part 1 Getting Started

To runa code example from the Code window:


1 Copy the example to the Code window as described above.
2 In the Object box, choose Form.
3 lf it's not already displayed, choose the Click procedure in the Procedure box, A
template for the Form_Click event procedure is displayed in the Code window.
4 Type the name of the example code procedure, "LineDemo," in the body of the Click
event procedure, as shown in Figure 4.7.

· Sub Form Click ()


· LineDemo
: · End Sub

Figure 4.7 The Form_Click procedure with LineDemo entered

5 From the Run menu , choose Start, or press F5.

6 Click the form. Visual Basic executes th e LineDemo procedure.


Each time you click the form , the LineDem o code will run again .
7 When you're fini shed, choose End from the Run menu .

To runa code example from the lmmediate wi ndow:


1 Copy the example to the Code window as desc ribed above .
2 From the Run menu, choose Start, or press FS .

3 Press CTRL+BREAK and click the Immedi ate window to bring it forward .
4 Type the name of the procedure, "LineDemo,"' in th e lmmediate window and press
ENTER .

To run the demo again , place the cursor aft er th e word LineDemo and press ENTER .
5 When you ' re finished , choose End from th e Run menu .

There are a few language topics whose exampl es mu st be divided between form code and
the global module. Those examples are clearl y marked by comments in the first few lines of
the example, as shown in Figure 4.8 . The procedure followin g the illustration describes how
to copy and run such a piece of code (in thi s case , th e example for the Global statement).

Microsoft Visual Basic Programmer's Guide


Chapter 4 Using Help 31

Visual Basic Help - VB.HLP

--
[ile ];_dit Bookmark tlelp
~ ••::-. ~H
lnde• Back
'Global Statement Example
Global TestArray() As Integer Put these two lines
Global Size As Integer global module .
Cut these lines
and paste into
Sub Globa lDemo global module.
Size = Int(lOO * Rnd + 1 ) Generate random s1ze
ReD1m TestArray (S ize ) Define how many elements .
For 1% = 1 to Size Index for number o f elements
TestArray(I %) = 1% Put number in each element .
~

Figure 4.8 An example with code that goes in the global modu le

To runa code example that must use the global module:


1 Copy the exarnple from Help to the Code window as described earlier.
2 In the Code window, select "(declarations)" from the Procedure box .
3 Cut the appropriate lines out of the Declarations section usi ng Cut from the Edit menu,
or SHIFf+DEL.
4 In the Project window, double-click the li sting for the global module.
5 Paste the lines into the Code window for th e global module.
6 Run the code from the Code window or the lrnmediate window as described above.

Microsoft Visual Basic Programmer's Guide


Part 2 introduces you to th e process of crcatin g appli cation s wit h Visual
8asic. Thc e mphasis is on fund ame ntal ski li s and co nccpts. Chaptcr 5
pnw idcs an ove rvicw or how Vi sual Basi c wo rk s by walkin g you through th
crca ti on ora simpl e -- Heli o. worl d' .. appli cati on. Chapters 6, 7. and 8 go into
more J ctail about usin g th c Visual Basic interfac e. and show you how t0
build a sli ghtl y more compli cat cd appli cati on - an inves tment ca lculator
that yo u rn ay find useful.
T hc nc.\ t pan or thi s boo k. Part J ... Appli ca ti on-Buildin g Tec hniques,"
L"O\'crs th c dctails or writin g code in th e Vi sual Basic lan guage. Detailed
info rrna ti on abo ut indi vidual co nt ro ls. propc rti cs. and eve nts can be found in
th c Lu11g11uge Refe rence . and in Hclp .
You ab o can lea rn th e run da rn cnta ls of deve lopin g appli cations witµ Visual
Ba-. ic by goin g th ro ugh th c Tut orial.
Overview of Visual Basic Development

Microsoft Vi sual Bas ic simplifies programm in g fo r the Microsoft Windows and Prese ntati on
Manager environments. With Vi sual Basic . yo u create th e entire use r interface for your
~- appli cati on without writing any code . Thcn. to make th e interface fun ctional , yo u attach code
th at responds when th e user clicks a button or oth erwi se interacts with the interface.
Thi s chapter explain s th e Vi sual Bas ic rnoJel by showing yo u how to create a simpl e
app licati on. lt then prov ides detai ls on \\'Orki ng with Visual Basic ril es. in cludin g how to
save yo ur work.
The main secti ons in thi s chap ter are:
• Your First App licati on
• Worki ng with Proj ec ts
• Sav ing Your Work

t .
36 Part 2 Visual Basic Essentials

Vour First Application


To give you a feel for how thin gs wo rk in Vi sual Bas ic, this section leads you through
building an application that di spl ays " He li o. world! " on the screen in response to a mou se
click. Sorne of the term s and conce pts may be new to you ; they ' ll be more fully explained in
the chapters that follow this o ne .
As -you read thi s section , keep in mine! th at there are three general steps for creating a Vi sual
Basic application:
1. Draw the objects that make up yo ur user interface.
2 . Set properties for the obj ec ts to change the ir appearance and behavior.
3. Attach code to the objec ts.

Starting Visual Basic


If you went through Chapter 2. ""Setu p," Vi sual Bas ic should be installed on your compute r.
You can start Visual Basic from the Fil e Manager in Windows or Presentation M anager by
doubl e-clicking the icon for VB. EXE. or by choosin g Run from the File menu ancl typing
vb . From DOS , you can start Vis ua l Bas ic by typing win vb at the system prompt.
To reduce screen clutter, you may wa nt to set th e Windows options so that Program
Manager is minimi zed when yo u start Visual Bas ic . To set that option, choose Minimi ze o n
Use from the Options menu in Prog ram Manage r. lf you plan to start Vi sual Basic fro m the
File M anager, set the same op tion there.
Wh en you start Visual Basic, it auto maticall y ope ns a new project and di spl ays th e Projec t
window . The application is th e ac tu al program the user run s, while the proj ect is th e set o f
fil es th e developer uses to build the applicati o n. The Proj ect windo w conta ins a li st of eac h
fil e in th e project.
Althou gh there is always a projec l open in Vi sual Basic, you can clase the Project window .
To open it again, choose Project W indow fro m th e Winclow menu. Visual Basic hieles th e
Project window when you run an app li ca ti on.
Fig ure 5. 1 shows what th e Project window loo ks like wh en you start Visual Basic .

Figure 5.1 The Project Window

Microsoft Visual Basic Programmer's Guide


Chapter 5 Overview of Visual Basic Development 37

For more information on projects, see the next section, "Working with Projects."

The Parts of an Application


A Visual Basic application can include three kinds of files: forros, modules, and a global
modul e. A form is a file that contains visual elements plus code, while the module and
global module file s are only code. ~ '
You work with forros and modules at design time, which is any time yo u' re building an
application. When you switch to run time by running the application , Visual Basic hides the
modules, and di splays only the forros you've programmed to be visible at startup .
The "Helio, world!" application uses only one form, but many of yo ur applications will use
two or more. To create a new form, choose New Form from the File menu.

Forms and Controls


Visual Basic uses the term "form" to refer to a window you create and customize, as
opposed to a built-in window such as the Project window. On forros, you draw graphical
objects called controls, which are used to get user input and to display output. Controls
include text boxes, comrnand buttons, and list boxes.
For more information on forros and controls, see the Language Reference , or:

m Search Help for:


objects

Much of the work you do with Visual Basic involves customizing forms and co ntrol s.
Because they are built into Visual Basic, you don't have to do any programming to display
them on the screen. You simply draw them to create your application' s user interface.
Drawing controls is much like drawing an object in a graphics program such as Windows
Paintbrush. To draw a text box for the "Hello, world!" application , cli ck the tex t box too! in
the Toolbox, shown in Figure 5.2. (The Toolbox is a set of tools you use at design time to
place con trol s on a form.) Then móve the pointer to the form and d1:ag to draw a text box .
Repeat the process for the command button .
.
~ fM
-
A @fil Text box too/

~
o -o - -
Command button too/

Figure 5.2 Text box and command button tools in the Toolbox

Microsoft Visual Basic Programmer's Guide


38 Part 2 Visual Basic Essentials

The result is a form w ith two controls, as shown in Figure 5.3. Each of these items - the
form and eac h con trol - is considered an object by Visual Basic code.

la Formt aa
1 >:: ::: ...

Figure 5.3 Te xt box and command button controls on a form

Fine-Tuning Vour Interface with the Properties Bar


After you draw co ntrol s on a form , yo u adjust their appearance and behavior by usin g th e
Properties bar, whi ch is located beneath the menu bar, as shown in Figure 5.4.

Eile .!;_dit Code Bun ':6:'indow !:!elp


ICt1Name 3000. 1800 l-'L::11.; 121 5 X~95

Figure 5.4 The Properties Bar

Every characteri stic of an object in Visual Basic is specified by a property. These


characteri stics include the objec t's name, contents, size, position, and color. Visual Basic
defines a specific se t of properties for eac h type of object. When an object is c reated. Visual
Basic sets its properties to initial (default) values. The value of a property is called a se tting.
As you design your appli cati on. you se t properti es to fashion the look of yo ur interface.
When users run yo ur application , th e code you' ve written monitors and ofte n changes
property settings in response to user actions such as mouse c licks.
You change property se ttings at design time by using the Properti es bar. To create the
"Hello, world !'' exa mpl e, yo u se t the fol lowi ng three properties .
Property name Meaning
Ct!Name The name of a control as it appears in Visual
Basic code.
Text The contents of a text box , Iist bo x, or
co mbo box.
Capti on The text displayed on a comma nd button ,
opti o n button , check box , o r a number of
other control s.

Visual Basic g ives th e tex t box th e defau lt name Textl and the comm and button th e defa ult
name Command 1. but it 's helpful to use more meaningful names so you ca n eas il y refer to
them in code. In this exam pl e, we ' II use the names Readout and HelloButton .

Microsoft Visual Basic Programmer's Guide


Chapter 5 Overview of Visual Basic Development 39

Click the text box once, then look to see whether the CtlName property is selected in the
Properties list box at the left of the Properties bar. (If it 's not selec ted, click the a1rnw at the
right of the list box and select Ct!Name.) Then type Readout. As you type, the text appears
in the Settings box in the rniddle of the Properties bar, as shown in Figure 5.5 .

lct1Name 11) 3000. 1800

Figure 5.5 The Properties bar with CtlName property set to Readout

Now click the command button and type HelloButton, then press ENTER. You've just
assigned new values to the CtlName property for each control.
Although the words you typed appeared in the Properties bar, you didn't see any change in
the text on the controls themselves. That's because Readout and HelloButto_n are control
names that appear only in code. The way to tell that a con trol name has changed is by
opening the Code window and looking at the code for the control. The Code window is
where you write, display, and edit Visual Basic code. You can open a Code window for each
form and module in your project. Double-click th e Readout text box to see what code is
attached, as shown in Figure 5.6.

O bject: i
R eadout

Sub Readout_ Change ()


End Sub

+ . •

The name Readout represents the text box in code.


Figure 5.6 The Code window with code for the Readout text box

You ' ll return to the Code window when you start addin g code. For now, close it or minimize
it, and continue setting properties.
The CtlName property settings for the text box and co mm and putton don ' t affect what the
user sees, but the Text and Caption property settin gs do ._The Text property for the text box
specifies the contents of the text box, and the Caption pr'ciperty for th e command button
specifies the text displayed on the button.

Note When you create a text box , Visual Basic initiall y sets th e Ct!Name property and the
Text property to the same default value ..:_ in thi s case, Text 1.

Microsoft Visual Basic Programmer's Guide


40 Part 2 Vi sual Basic Essentials

For the "Helio, world! " application, you want the text box to start off empty. You do that by
setting its Text property toan empty string.

To change the text box so it displays an empty string on startu p:


1 Click the text box .
2 Click the arrow in the Properties list box at the left of the Properties bar.
Vi sual Basic di splays a list of ali the properties defined for the text box .
3 Press the letter T until the Text property is selected, then press ENTER .
4 Select the existing text in the Settings box, press DELETE, and then press ENTE R.
The text box should now be blank.

Now, you change the caption displayed on the HelloButton command button .

To change the command button so it displays "Click Here":


1 Click the command button.
If the Caption property is selected in the Properties bar, skip to Step 4.
2 Click the arrow in the Properties list box at the left of the Properties bar.
Vi sual Basic di spl ays a list of ali the properties defined for the command button .
3 Press the letter C until the Caption property is selected, then press ENTER .

4 Type Click Here


As you type, the new caption appears on the command button.

With the interface for the "Hello, world!" application complete, you ' re ready to add the code
th at tell s the command button how to respond to a mouse click at run tim e.

Writing Code to Respond to Events


Earli er yo u read th at each object (form or control) has a predefined set of properties, and th at
each of these properties has an initial value you can change at design time .
Similarly, eac h object you create is associated with a predefined set of eve nts. An e vent is a
specific action , such as a mou se cl ick, that is recognized by a form or control. An eve nt
typically occurs as a result of a user action, but may also be generated by the sys te m.
Although obj ec ts in Visual Bas ic automatically recognize a predefined set of eve nts, yo u
determine if and how they will respond toan event. You program the res pon se by writin g
code. You don ' t have to write code for every combination of object and eve nt. I f an object
recognizes an event, but there is no code attached for that event, Visual Bas ic ignores it.
When you do want an object to respond toan e vent, you put the instructions in th e form of
cude called an event procedure.

Microsoft Visual Basic Programme r's Guide


Chapter 5 Overview of Visual Basic Oevelopment 41

An Event Procedure for the Command Button


To make the HelloButton command button respond to a mouse click at run time, you write
code for the Click event. First, double-click the command button to open up the Code
window for the form.
When you double~click a command button, the Code window selects the Click event by
default, as shown at the left of Figure 5.7. But you ca~write code for any of the events
recognized by the command button. To see a list of those events, click the arrow in the
Procedure box , as shown at the right of Figure 5.7. Click the arrow again to close the lis t.

Objecl: jHe lloB utton


Sub HelloButton_Click ()

End Sub

Sub HelloButton_ Click () DragDrop


DragOver
End Sub GotFocus
Ke¡,Oown
KeyPress
KeyUp
LostFocus


+ +

Figure 5.7 The Code window with the Click procedure displayed, and with a list ot other events

The Procedure box lists al i of the events recognized by the current object (i n this case, the
command button). When you select Click in the Procedure box, Visual Basic displays acode
template for the event procedure HelloButton_Click. Acode template includes the first and
last lines of an event procedure.
An event procedure is the code that is invoked when a form or control recognizes that a
particular event has occurred. Visual Basic knows which procedure to invoke because the
name of the procedure includes the names of both the object and the event, joined by an
underscore, like thi s:
objectname_eventname

The objectname is the same as the value of the Ct!Name property. The eventname must be
on the li st of events that Visual Basic defines for the object. Because the naming convention
establishes a link between the object and the code, event procedures are said to be attached
to forms and controls.

Microsoft Visual Basic Programmer's Guide


42 Part 2 Visual Basic Essentials

How Things Happen in Code


Earlier, yo u learned how to use the Properties bar to change initial settings for properties. To
change a property setting at run time, you entera Visual Basic statement with this syntax:
obj ectname.propertyname = new setting

The. text box in the "Helio, world!" application is named Readout, and the Text property
determines what it displays. Therefore, the line of code that prints "Hello, world !" is :
Readout.Text = "Hello, world!"

Enter that line between the Sub and End Sub statements in the HelloButton_Click
procedure. Figure 5.8 shows what the completed procedure should look like, and it also
points out what each part of the procedure does.

Procedure name determines what event to respond to.

Sub HelloButton_ Click ()


Readout.Text = "Hello, world!"
End Sub

• •
.
Name after the period determines what property to change.
Name befare the period determines what object to act on.
Figure 5.8 The Code window with the completed HelloButton_Click procedure

Now yo u can press F5 to run the application. To make sure the code works, click th e
command button; the words "Heli o, world !" should be displayed in the text box . Choose
End from the Run rnenu to retum to design tim e.
To create a variation, you can add a statement that causes the command button to display the
text , "You clicked me!" Although yo u use the Text property to specify what is displayed in
text boxes, you use the Caption property to specify what appears on buttons . The event
proced ure with the add itional line of code should look like this:
Sub HelloButton _ Click ()
Readout.Text = "H ello, world!"
HelloButton.Caption = "You clicked me!"
End Sub

Microsoft Visual Basic Programmer's Guide


Chapter 5 Overview of Visual Basic Development 43

You ' ve now drawn control s, set properties, and written code to create a simple application in
Visual Basic. The las t secti on in thi s chapter, "Saving Your Work," explains how to save what
yo u' ve done.
For more information on the steps in building an application, see Chapter 6 , "Drawing t:1e
Interface," Chapter 7 , " Settin g Properties," and Chapter 8, "Attaching Code," or:

m Search Help for:


build a See Tutorial Lesson:
"Working with Visual Basic"

You tested the "Helio, world !" application by running it inside Visual Basic. You also can
co nvert an application to an executable file so that it can run outside Visual Basic. For more
information, see Chapter 8, or:

m Search Help for:


exe cutable a See Tutorial Lesson:
"Working with Visual Basic"

Working with Projects


The prev ious section defined a proj ec t as a collection of all the fil es that make upan
applicati on. Visual Basic di spl ays a listing for each fil e in the Proj ect window. A projec t has:
• Zero or more form file s. Stored in each fil e are the visual representation of the form and
the controls drawn on it, event procedures attached to the form and control s, and general
procedures not attac hed to objects. Most applications include at least one form .
• Zero or more module files. A module is -a collection of general procedures that can be
called from anywhere in the application. ~_oduJes are_us~d_in larger_applications to store
p.!:_oc~d ures shared by the entire applica,~j_Ql) . · - · -
• G lobal module fil e. The global module stores variable, constant, and type information
shared by the entire application . The global module has no procedures. There is always
one (and onl y one) global module in a project, but like regular modules, you don ' t have
to use it.

For a co mplete di scuss ion of modul es and the global module, see Chapter 17 , "Advanced
Language Features ."

Opening and Closing Projects


As men ti oned earlier, when yo u start Vis ual Basic, it aut_omatically opens a new projec t. To
ope n an ex istin g project, choose Open Project from the Fil e menu . You cannot have more
th an one project open at a tim e, but yo u can copy controls and code from one proj ect to
another.
You do not close a proj ec t as yo u woul d a file . Instead, a proj ec t is closed whe n yo u quit
Vi sual Basic , or when yo u ope n another new or existin g proj ec t. In each case, yo u will be
prompted to save th e project you were working on. For more inforn1ation on saving the fil es
in a project, see the sec ti on "Saving Yo ur Work" at the end of thi s chapter.

Microso ft Visual Basic Programmer's Guide


44 Part 2 Visual Basic Essentials

Where Project Files Are Stored


When you open a new project, Visual Basic creates a blank form and a global module. The
form is automatically opened in the center of your screen, and the Project window di splays
li stin gs for the form and the global module .
However, although the listings in the Project window represent fil es, Visual Basic does not
automatically create files on your di sk when you open a new project. Only when you choose
one of the Save comrnands from the File menu does Visual Basic actually save anything to
disk.
When you choo se Save Project, Visual Basic first prompts you to save each of the forms in
the project with the default extension .FRM. It then prompts you to save the project fil e with
the default extension .MAK. The project file does not contain any forms or code. It is simpl y
a Ii st of all the files associated with a particular project. That list is updated every time yo u
save the project.
The files that make upa project don't have to be in one direc tory on your hard drive,
because the project file tells your application where to fi nd them . In addition, a single file ,
such as a form, can be part of more than one project. When you build an executable version
of an application, Visual Basic copies the form and module files and combines the copies
into one executable file, but leaves the original files intact.

Note 1f you delete or rename a fil e from inside Vi sual Basic using the Remove File or Save
File As commands on the File menu , the project fi le is updated to reflect those changes the
nex t time the project is saved. However, if yo u rename or delete a file outside of Vi sual
Basic and then open the project, Vi sual Basic display s an error message to warn you th at a
file is mi ssin g. To add a new or renamed file into a project, open the project and choo se the
Add Fil e command from the File menu .

Microsoft Visual Basic Programmer's Guide


Chapter 5 Overview of Visual Basic Development 45

Saving Vour Work


Visual Basic prompts you to save the files in a project to di sk whenever changes would
otherwise be lost (for example, when quitting Visual Basic) . However, it 's a good idea to
save regularly while yo u're creating an application.
When you save a {01m file , you also save any code you ' ve attached to both the form and
controls. However, you also can save the code separatefy, as text. The following tabl e
explains the Save comrnands that are available in Visual Basic.
Save command Action
Save Project (File menu) Saves all th e files in the current project and
the project file itself in binary formal.
Save Project As (File menu) Like Save Project, but enables you to save
the project file under a new name while also
retaining the original file.
Save File (File menu) Saves the currently se lected form or modul e
in binary formal.
Save File As (File menu) Like Save File, but enables yo u to save a file
under a new name while also retainin g the
origi nal file. The new file remains in the
project, but the original file is closed and
removed from the project. (See note below .)
Save Text (Code menu) Saves the code in the currently selected
form or module in text (ASCII ) formal.

Note The Save File As comrnand saves the file, and any changes made since the last save,
unde r a new name that you specify. The old version of the file, without a ny of the changes
made since the last time you saved, is retained also. However, only the newly named file
remains associated with the project. You can add the old version back into the project by
using the Add File command from the File menu.

For more information on saving your work :

m Search Help for:


save

Microsoft Visual Basic Programmer's Guide


Drawing the Interface

The fi rst step in creating an appli cation with Visual Basic is to dra w the user interface: th e
command buttons. tcxt boxes , and oth er objects the user will see and use. You th en set
propert ies and write Vi sua l Basi c code to make the interface ac ti ve.
Thi s chapter ex plain s how to draw the interface for an application th at calcul ates th e re turn
on an investment. Chapter 7, ··Setting Properties," and Chapter 8, "Attaching Code,"' use thc
same examp le. lf yo u work at your computer as yo u read throu gh the next three chap ters,
you' ll end up with a rully func ti onal investment calculator.
The main sectiom, in thi'.:. chapter are:
• Drawin g Controls
• Resizing. Mo\'ing . and Deleting Control s
• Saving the In vestmcnt Calcul ator

11
.---·:...
'-...~ •-t:•:-.
. ··... ··.......
··:::..
..
··-.:·-.. ·-==·
··-.:~
..·-·:.
'··{ : ~· :--,......
· . ·. 0··
··..:· --#
- ·-
Part 2 Visual Basic Essentials

Drawing Controls
Chapter 5, "Overview of Visual Basic Development," explained that you draw controls on
forms to create the interface for your application. This chapter provides more detai ls on
drawing controls and how to move and resize them once they're drawn. Although each type
of control is different, you use the same process to draw al i co ntrol s.

The Toolbox
The center of the drawing process is the Toolbox, which you can position anywhere on the
screen. It contains one tool for each control, plus a pointer to manipulate controls after
they ' re drawn. You use the tools to draw controls on a form muchas you would use tools in
a graphics program to draw lines and shapes.
The Toolbox opens automatically when you start Visual Basic. If it has been closed, you can
open it again by choosing Toolbox from the Window men u. Figure 6.1 shows the Toolbox
with its tools labelled .
.
Pointer - ~ ~ - Picture box
Label - A ~ - Text box
Frame - oo - Command button
Check box - [8J @ - Option button
Combo box - ~. gJ - List box
Horizontal sera// bar - 8!] ~ - Vertical sera// bar
Timer - o
. El - Orive list box
Directory list box - o ~ - File list box

Figure 6.1 The Toolbox

This chapter describes only the controls used to build th e In ves tmcnt Calc ulator in the nex t
section . For information on ali Visual Basic controls, see the individuaJ entri es on controls in
the Language Reference, or:

m Search Help for:


contro ls a See Tutorial Lesson:
"Working with Visual Bas ic"

Microsoft Visual Basic Programmer's Guide


Chapter 6 Drawing the Interface 49

The Interface of the lnvestment Calculator


With Vi sual Basic, it' s possible to build a useful application such as an Investment
Calculator by drawing only a few controls and writing relatively simple code. The
calculator, shown in Figure 6.2, computes the endin g bal ance of an investment when interest
is compounded daily.

Starting Balance '-----__J.____ _ _ ___,' - Text box

lnteres t Rate in %1._5___ _ __,

1
Duration in Y ear s .
1 ____ _ __,

¡Compute Ending Balance ¡ ~ - -------&- Command button

1 5 13
Ending Balance . _º _- _ _
l ___ __J

Figure 6.2 The Completed lnvestment Calculator

As yo u can see, the lnvestment Calculator uses three types of controls: labels, text boxes,
and a command button. A label displays text th at cannot be directly changed by the user. A
text box provides a place to display or enter text, and a command button is a control that can
be programmed to carry out a command or ac tion when the user clicks it. (Sorne other
products refer to command buttons as "push buttons," and to text boxes as "edit fi elds.")
The first three text boxes accept input for th e startin g balance, interest, and duration of the
in ves tm ent. The command button starts the computation and displays the result in the fourth
tex t box. The labels show the user wh at each text box contains.

Microsoft Visual Basic Programmer's Guide


50 Part 2 Visua l Ba sic Ess enti als

Drawing a Text Box


You can start to build the lnvestment Calculator by opening a new project and followin g the
steps below to draw a text box on the blank fonn . Then use the same procedure to draw the
rest of the controls. When you ' re done, your form should look like Figure 6.3 . Notice that all
of the co ntrol s di splay their default names - he names assigned by Visual Basic. You ' ll
leam how to change default names in Chapter 7, "Setting Properties ."

1m Forml aa
: : Labell IText1
: : : Label2
~ITe-xt2- ~I
Labe13 1 Tesl3

Command1

Label4 IText4

Figure 6.3 Controls with default names

To draw a text box:


1 lf th e Toolbox is not visible, choose Toolbox from the Window menu .
2 Click th e text box too] , as shown in Figure 6.4 .

Texr box too /

Figure 6.4 Text box tool selected in the Toolbox

Microsoft Visual Basic Programmer's Guide


Chapter 6 Drawing the Interface 51

3 Move the pointer onto your form . The pointer becomes a cross hair, as shown in
Figure 6.5.
a

~ ~
mi Forml aa
A ~
oo 1 ¡:.::
··· ~ - - - -
. +. :::
181 ®
~. ~.
[fil)
fil
o El
cJ ~

Figure 6.5 Orawing the text box

4 Place the cross hair where you want the upper-left comer of the control.
5 Drag the cross hair until the control is the size you want.
6 Release the mouse button. The text box appears on the form .

To complete the interface, draw three more text boxes, four labels, and a command button .
You can draw them using the steps above, or use the shortcut described in the next section .
Figure 6.6 shows where the label and command button tool s are located in the Toolbox .
After drawing the controls, arrange them as shown in Figure 6.3 .
.
~ ~
r:--;
A = La bel too!

oo ,-- Command button too/


¡g¡ @
- - -
Figure 6.6 The label and command button tools in the Toolbox

For information on how to manipulate co ntrol s, see "Resizin g, Moving, and Deleting
Controls" later in thi s chapter, or:

m Search Help far:


manipulate controls a See Tutorial Lesson:
"W~king with Visual Basic"

Microsoft Visual Basic Programmer's Guide


52 Part 2 Visual Basic Essentials

A Shortcut
If you follow the steps in the procedure above for drawing a text box , you can select, place,
and size each control in turn. However, if you have a lot of controls to draw, you may find it
fas ter to crea te all of the controls first , and then arrange them on the form. Y ou can crea te a
default-size control, without drawing it, by doubl e-clickirig the appropriate too! in the
Toolbox .

To create a control by double-clicking:


• In th e Toolbox , double-click the too! for the co ntrol you want to create.
The control appears in the center of th e form . When you double-click agai n, another
control appears on top of the first. You then ca n move each control to where you want it.

You can create ali of the controls you need for the Investment Calculator by double -clicking
the appropriate tool s in the Toolbox , and then moving the controls until they are arranged as
show n in Fig ure 6.3. You can resize controls as ex plained in the next section , but you'll
act ually save time if you wait to resize the co nt ro ls until after you've set the captions. That
way you ca n be sure that the captions fit in the control. Setting captions is explained in
C hapter 7, "Setting Properties."

Copying and Pasting Controls


You can copy and paste controls within a form or from one form to another. Thi s is hand y if
you want to quickly create severa! identical co ntrols. For more information :

m Search Help for:


copy controls
111111
U
See Tutorial Lesson:
"Working with Visual Basic"

Microsoft Visual Basic Programmer's Guide


Chapter 6 Drawing the Interface 53

Resizing, Moving, and Deleting Controls


After you draw a control yo u can change its size, move it, or delete it. Resizing and moving
are essential if you create controls with the double-clicking shortcut.

To resize a control:
1 Click the control to select it.
The control is outlined with small black rectangles called sizing handles, as shown in
Figure 6.7.

mi Forml aa
...

I Text1 1- • _ Text2~
'1---i ~~~- [

Click control to display


sizing handles.
Figure 6.7 A selected text box displays sizing handles.

2 To size the heigh t and width of the control at the same time, drag one of the com er sizing
handles.
To size the control in one direction only , draga sizing handl e on one of its sides.
3 Release the mouse button to redraw the control to the new size .
To cancel the selec ti on, cli ck an em pty part of the form .

To move a control:
• Posi tion the pointer anywhere inside the border of the control and drag it to the new
location on the form .

You can move a control that ' s already selec ted, but be careful not to drag one of the sizing
handles. When you re lease the mouse button after moving a control , the sizing handles will
be di splayed (even if they weren't before the move) .

Microsoft Visual Basic Programmer's Guide


54 Part 2 Visual Basic Essentials

To move two or more controls at once:


1 Press the CTRL key and click each control you want to move.
(You don ' t have to press CTRL to select the first control. )
As you click each control, it' s outlined with gray sizing handles, as shown in Figure 6.8 .

mi Forml aa
•.. CTextl :

1 Multiple-selected controls
Figure 6.8 Multiple-selected controls are outl ined with gray sizing handles.

2 Drag the selected controls to the new location on th e form .


To cancel the selection, click an empty part of the form .

To delete a control:
1 Click the contro l to select it.
2 Press the DEL key .
- or-
From the Edit menu , choose Delete.

To delete two or more controls at once:


1 Press the CTRL key and click each control you want to delete.
2 Press the DEL key .
- or-
From the Edit menu , choose Delete.

Aligning Controls on the Form


When you move a control, you may notice that it "jumps" by small increments. What's
happenin g is that Vi sual Bas ic is movin g it along a built-in grid. The grid is di splayed as
dotted lines in the backgro und of every form at design tim e.

Microsoft Visual Basic Programmer's Guide


Chapter 6 Drawing the Interface 55

The grid is there to make it easier for you to line up controls. If you want to move controls
by increments smaller th an the grid allows, choose Grid Settings from the Edit menu and
tum off the Ali gn to Grid option. When you tum the grid back on, you can use the Align to
Grid command on the Edit menu to line up selected controls on the grid. You also can
change the increments for the grid by typing in new Spacing se ttin gs in the Grid Settings
dialog box.
For more information on using the grid:

111 Search Help for:


grid a See Tutorial Lesson:
"Working with Visual Basic "

Saving the lnvestment Calculator


This chapter walked you through the first stage of building the Inves tment Calculator:
drawing th e control s. The nex t two chapters use the same example, so you should save your
work if you want to con tinu e building the application .

To save the files in the lnvestment Calculator:


1 From the File menu, choose Save Project.
If you have not previously saved the project, Visual Basic displays the Save File As
dialog box asking you to provide a name for the form.
2 Type invest.frm
3 Choose OK or press ENTER to save the form.
Visual Basic displays the Save Project As dialog box ask in g yo u to provide a name for
th e project.
4 Type invest.mak
5 Choose OK or press ENTER to save the project.

For more information on saving your work, see Chapter 5 , " Overview of Visual Basic
Development," or:

111 Search Help for:


save a See Tutorial Lesson:
"Working with Visual Basic "

Microsoft Visual Basic Programmer's Guide


Setting Properties

Chapter 6, "Drawing the Interface," took you through the first steps in building an
application. Working with a bl ank fo rm as the framework , you drew co ntrol s and set their
size and locati on to make a "rough draft" of yo ur application' s interface. Now yo u can refine
the interface by fine-tuning the appearance and behavior of the control s.
You accompli sh thi s fine-tuning by settin g properties. For exampl e, you ca n add a border to
a label control by setting its BorderSty le prope rty to 1. Or, you can set the MultiLine
property for a text box to True so it ca n acco mm odate multiple lines of tex t.
Thi s chapter explain s how to set properti es at desig n time usin g th e Properti e bar. It
continues the creation of the ln vestm ent Calcu lator described in C hapter 6 by show ing yo u
how to set properties for the objects th at mak e up that app li catio n. The main secti ons in thi s
chapter are:
• The Role of Properti es in Vi sual Bas ic
• U ing .the Properties Bar
• Setti ng Properties for the In vestment Ca lcu lator
• Other Ways to Se t Prope rtie ~

X X >
58 Part 2 Visual Basic Es se ntials

The Role of Properties in Visual Basic


Eac h objec t (fo nn or co ntrol ) in Vi sual Basic has a predefined set of properties. These
properti es determin e the object 's appearance and behavior. For example, the Enabled
prope rty determ ines whether a text box can respond to events, while the FontBold propert y
determines wh eth er text is di splayed in a bold font.
When an obj ec t is created, its properties are set to initial values, called default settings. A
default setting is th e valu e a property has if you do nothing to change it. For exampl e, the
default setting fo r the Enabled property is True - which means the property is "on ." So,
unless you specify otherwise, ali form s and controls are enabled and can respond to events.
In man y cases yo u' ll find th at default settings work fine. You don ' t have to set the value of
every property of an obj ec t - only the ones in which you want a different value from the
default.
You set propen ies at design time using the Properties bar, and at run time using code.
Changing property settings at run time is one of the keys to making an application work . For
information on se tting properti es at run time, see "Other Ways to Set Properti es" later in thi s
chapter, or Chapter 8. "Attachin g Code."
For explanati ons of al i Visual Bas ic properties, see the Language Ref erence, or:

m Search _Help for:


propert,es
111111 See Tutorial Lesson:
111 "Working with Visual Basic "

Using the Properties Bar


The Properti es bar is located beneath the menu bar, as shown in Figure 7 .1. You use it to
vie w and se t prope rti es fo r the selected control or form .

To see the properties for a form:


• Click a blank pa rt of the fo rm .
The fo rm 's propert ies are di spl ayed in the Properties bar.

To see the pro perties for a control :


• Cli ck the cont ro l.
- Or -
• Press TAB to se lec t the control.
The control" s prope rti es are di spl ayed in the Properties bar.

Microsoft Visu al Basic Programmer's Guide


Chapter 7 Setting Properties 59

To change a property setting for a form or control:


1 Click the control or a blank part of the form .
2 In the Properties list box at the left of the Properties bar, select the property you want to
change.
3 Type the new setting.

Type a new setting here.

X ✓ Commandl 1800. 2760 ~i::1


1 2535 X 375

Cursor
Default
Draglcon
DragMode
Enabled
FontBold
Fontltalic
FontName •

Click here ar press ENTER to


confirm the new setting.
Figure 7.1 The Properties Bar

4 To confirm the setting you've typed, press ENTER, or click the Enter button (the one with
a check mark).
To cancel the new setting, press ESC, or click the Cancel button (the one with an X) .

The Properties li st box at the left of the Properties bar lists all of the properties you can se t
for the selected object at design time. (Sorne properties can be set only at run time .) The
Properties list box always di splays one property for the selected object, and you can cli ck the
arrow at the right of the li st box to scroll through a list of other properties for that object.
You then can click one of the properties to select it and to display its setting in the Settings
box at the middle of the Properties bar. The boxes at the right of the Properties bar display
the position and size of the selected object, both when it's in one place and while you move
or resize it.
Visual Basic makes it easy to change a property setting: You just select an object, select a
property, and type to change the setting. You don't have to select the setting in the Settings
box - you just type to rep lace it. _

Hint A quick way to find a property is to click the arrow in the Properties list box and then
press the first letter of the property name. The selection shifts to the first property th at starts
with that letter. Press the letter again to move to other words that begin with the same letter,
or use the arrow keys. Press ENTER and then type ro edit the property setting.

Microsoft Visual Basic Programmer's Guide


60 Part 2 Visual Basic Essentials

Sorne properties have a fixed list of se tting . For instance, the Visible prope11y , w hi ch
determ ines whether the user can see a form or control , mu st be either True or False. Rath er
th an typ ing new settings for such properti es, you click the arrow at the right of the Settings
box and choose from a list, as shown in Figure 7 .2.

f il e .!;_ dit ~ode B un '.:6'.indow !::!e lp


¡visible w 3000, 1800

FALSE

lf the arrow at the right of the Settings box is


ena bled, click the arrow and se/ect from the list.
Figure 7.2 The Settings box displays a list of possible settings far the selected property.

To choo se from a fixed list of property settings:


1 Click the control ora blank part of the fo rm .
2 In the Properties list box , selecta propert y.
If th e selec ted property has a fixed number of settings, the arrow at the right of the
Settings box is enabled (and shaded bl ack rather than gray) .
3 Cli ck the arrow.
Vi sual Basic displays a li st of poss ible se ttin gs .
4 Select the setting you wa nt from the li st.

Hint There's another way to chan ge se ttin gs for properties with a fixed number of settin gs:
Fo ll ow Steps I and 2 in the procedure above. then press the first letter of the settin g (such as
" F" for False), and press ENTER

Vi sual Basic also provides key combina ti ons yo u can use to see and set properti es in the
Properti es bar. For more informat ion :

m Search Help for:


Properties bar

Microsoft Visual Basic Programmer's Guide


Chapter 7 Setting Properties 61

Setting Properties for the lnvestment Calculator


In Chapter 6, " Drawing the Interface," you started a new project and drew controls as the
first step in building an Investment Calculator. Now that you know how to set properties,
you can continue building the application by changing the appearance of the controls.

Setting the Caption Property


The previous sec tion explai ned how to set properties for any object. You can practice what
you learned by settin g the Caption property for the command button in the Investment
Calculator. The Caption property determines what text is di splayed on the button . The
procedure ass umes yo u have started Visual Basic and opened the Investment Calculator
project, which you were asked to save as INVEST.MAK in Chapter 6.

To set the Caption property:


1 If necessary, open the form for the Investment Calculator by doubl e-c licking the
INVEST.FRM li sting in the Project window .
2 Click the co mm and button on the form.
The Properties bar di splays the properties for the command button . By default, the
property initi all y di spl ayed for a command button is Caption. So unless sorne other
property is di splayed , you can skip Step 4 and proceed to Step 5.
3 In the Properties list box at the left of the Properties bar, select th e Caption property.
The Caption property is di splayed in the list box, and its current setting is di spl ayed in
the Settings box at the middle of the Properties bar.
4 Type Compute Ending Balance
5 To confirm th e new se tting, press ENTER, or click the Enter button (the one with a check
mark).
You may need to resize the command button if "Compute Ending Balance" doesn' t fit.
Note th at Vi sual Basic autom ati call y centers text on the command button .

A Shortcut
Sorne of the app li cati ons yo u create with Visual Basic may require you to set a number of
properties for eac h of your controls. One way to do that is to set ali of the necessary
properti es for one control, then set them for the next control, and so on. However, that wi ll
mean repeated ly se lecting properties for each control. _
You can avo id th at by tak ing advantage of a handy fe ature: Once yo u selecta property, the
Properties bar co ntinues to di splay th at property for each object you select. That means you
can set one property-such as Caption-for each control to which it applies without having
to reselect the property in the Properties bar. You simp ly select the nex t control and type a
new settin g. Jf you se lec t an object to whi ch a property does n' t app ly, the Properties bar
di splays the default or most commonl y used property for th e selec ted object.

Micro soft Visu al Basic Programmer's Guide


62 Part 2 Visual Basic Essentials

To set the same property for severa! controls in succession:


1 Select the first control.
2 In the Properties list box at the left of the Properties bar, select the first property you
want to set.
3 Type the new setting.
4 Click the next control.
- or-
Press E TER, and then press TAB to move the selection from one control to the next.
(When you click the next control, you don't have to press ENTER to confirm the change
for the previous control; Visual Basic confirms it automatically .)
5 Repeat Steps 3-4 until you have set the first property for each of the co ntrols to which it
applies.
6 Repeat Steps 1-5 for each of the properties you want to set.

Setting Other Properties for the lnvestment Calculator


Now that you've set the Caption property for the command button in the Investment
Calculator, you can set properties for the other controls. Figure 7 .3 shows the Investment
Calculator before and after its properties have been set. You ca n see differences in what' s
displayed on each control, but you'll be making other changes, too.

1m Forml aa 1m lnvestment Calculator aa


Labe ll • , Te•t1
,....
.: :
Sta,ting Balance
1 1

Label2 : 1Te•t2 .. lnte,est Rate in ~


1 1 1

Label3 j Te•t3 Ou, ation in Years:


1 •

Command1 Compute Ending Balance


1 1

. : . Labe l4 : ITe•t4 1
E nding Balance

Figure 7.3 The lnvestment Calculator befare and after properties are set

As mentioned earl ier, you often don ' t need to c hange th e default se tting for a property . The
following table lists the properties you do need to set for eac h co ntrol in the ln vestm ent
Calculator. The first column lists the default name th at Visual Basic assigned to each object
when you created it. The other columns list the settin gs for eac h property. Further
explanation follows the table.

Microsoft Visual Basic Programmer's Guide


Chapter 7 Setting Properties 63

In Chapter 8, "Attaching Code," you ' II finish the lnvestment Calculator by attaching code
to the command button.
Default name Caption CtlName Text
Forml lnvestment
Calculator
Textl StartTexi (blank)
Text2 RateText (blank)
Text3 YearsText (blank)
Text4 EndText (blank)
Labell Starting Balance
Label2 Interest Rate in %
Label3 Duration in Y ears
Label4 Ending Balance
Commandl Compute Ending CalcCmd
Balance

The Form
The Caption property places a caption in the form's title bar.

The Text Boxes


The Ct!Name property uniquely identifies eac h control you draw . You use thi s name to refer
to the control in code. It's a good idea to give objects descriptive names that help you
remember what they ' re for. The na mes used here for the text boxes identify what each holds:
StartText for the starting balance, and so on. The "Text" at the end of the name helps you
re member what type of control it is.
The Text property determines what te xt is displayed in a text box, or reflects what the user
has typed in at run time. The default se tting for the Text property is the same as its CtlName
property . That helps you tell one text box from another. However, for the lnvestment
Calculator, you want the text boxes to be blank so the user can enter numbers into them. To
make them blank, select the Text property in the Properties list box, then select the default
setting in the Settings box and delete it or replace it with a blank space.

The Labels
Labels have a Caption property that determines what text they display. When a label is
created, its Ct!Name property and Caption property are the same. It doesn 't matter whether
the default names for your labels match the default names in the table, as long as the
captions match the ones shown in Figure 7.3.

Microsoft Visual Basic Programmer's Guide


64 Part 2 Visual Basic Essentials

The Command Button


You may have already set the Caption property for the command button , but you must also
set its Ct!Name property so you can refer to it later in code. The name suggested for the
co mmand button ends with an abbreviation that helps you to keep the type of control in
mind - in this case, CalcCmd.

Other Ways to Set Properties


Setting properties at design time using the Properties bar is only one of three ways to change
properties. You also can set properties at run time - either by using code or, for most
co ntrols, by allowing the user to make changes.
The text box provides a good example of these methods. The following li st explains three
ways the Tex t property can be changed.
lf you want to Set the Text property by
Display a fixed message to the user. Typing the text in the Properties bar.
Accept input typed by the user. Typing a blank space in the Properties bar.
At run time, the user's input will
automatically reset the Text property .
Di splay text in response to sorne event (such Writing code that says, in effect, "assign this
as the results of a calculation). setting to the Text property." That setting
(the text) will be displayed in the text box
when the code executes .

Although most properties can be set from code, only a few can be se t directly by the user.
For more information about setting properties from code, see Chapter 8, " Attaching Code."

Setting Properties for Size and Position


The properties that determine the size and position of a form or control - Left, Top, Height, and
Width - are set automatically when you move or resize a control or form . These properties are
di splayed in boxes at the right of the Properties bar, and they chan ge as yo u move or resize an
object with the mouse. You cannot type in these boxes, but you can change properties for size
and position the same way you change other properties: Select them in th e Properties list box at
the left of the Properties bar and type new settings.

¡fj
1 2295 X ~95

Width x He,ght
Figure 7.4 Property settings for size and position

Microsoft Visual Basic Programmer's Guide


Attaching Code

Once yo u' ve finished creating an application ' s interface, yo u' re ready to attach code to the
objects in the interface to make them respond to events. ::You write that code in the Code
window.
This chapter explains the various features of the Code window, and reviews the structure of
the event procedures you write there. It also describes the event procedure that completes the
Investment Calculator you've been building in the previous two chapters. After you finish
this chapter, yo u should have a fully functional calculator - and you' 11 understand how it
works .
Details on programming in Visual Basic are provided in Part 3 of this book.
The main sections in thi s chapter are:
• When Do You Need Code?
• Writing Event Procedures
• How the Code Works
• Creating an Executable File

.....--
-
66 Part 2 Visual Basic Essentials

When Do Vou Need Code?


In traditional applications, ali of the functionality comes from the code you write. In Vi sual
Basic, a lot of functionality has been built into the forms and controls themselves . So it ' s
important to understand when code is and isn ' t necessary in building applications.
Simply put, you need code in Visual Basic to activate your interface, not to creare it in th e
firsi place . You don ' t have to write code to creare the objects that make up your interface,
but you usually do have to write code to make somerhing happen when users interact with
those objects.
For example, consider the Investment Calculator described in the previous two chapters and
show n in Figure 8.1. The user enters numbers in the text boxes (labeled Starting Balance.
lnteres t Rate in %, and Duration in Years) and then clicks the command button , Compute
Ending Balance. The application responds by di splaying rhe answer in the Ending Balance
text box.

S tarting Balance ~ - - ~ > - - - -- ---11- Text box

lnterest Rate in Z
5
~1___ ~

Ouration in Years l._1 _ __ ~

!Compute Ending Balance · ---- -- - - Comm and button

1 5 13
Ending Balance _º _- _ _ ~
~1

Figure 8.1 The completed lnvestment Calculator

To make the applicati o n work as described , you don ' t need to write an input statement to
allow the user to enter numbers in the first three text boxes. Text boxes have a built-in
capabilit y of accepting text. Nor do yo u need to program the fourth text box to be able to
di splay text - that functionality is a lso built in . However, you do need to write code to do
four things in thi s application :
• Ret ri eve th e text that the user types in the text boxes
• Convert th at text to nurnbers that can be used in a calculation
• Calculate the ending balance
• Format th e endi ng balance and display it in the Ending Balance text box

Microsoft Visual Basic Programmer's Guide


Chapter 8 Attaching Code 67

Because ali of these tasks are rela~ed to co mputin g and di splaying the ending balance, the
code can go into a single event procedure. And because you want the final calculation to
take place when the user clicks the command button, you'll attach the event procedure to
that button . Ali event procedures follow the same general format, as explained next.

Writing Event Procedures


When an object in Visual Basic recognizes that an event has occurred, it automaticall y
invokes the event procedure with the name that corresponds to the event. Because the name
establishes an association between the object and the code, event procedures are said to be
attached to forms and controls.
An event procedure for a control combines the control' s actual name (specified in the
CtlName property), an underscore, and the event name. For instance, if you want a
command button named M yButton to invoke an even.t procedure when it is clicked, use th e
procedure MyButton_Click.
An event procedure for a form combines the word "Form," an underscore, and the event
name. If you want a form to invoke an event procedure when it is clicked, use the proced ure
Form_Click. (Like controls, forms do have unique names, but they are not used in th e names
of event procedures. )

Note Although you can write event procedures from scratch, it's better to use the code
templ ates provided by Visual Bas ic, which automatic ally include the correct procedure
name. (The next section, "Using the Code Window," tells you more about templates .)

All event procedures use the same general sy ntax, as shown in the followin g table.
Syntax for control events Syntax for form events
Sub controlname_eventname () Sub Form_eventname ()
statementblock statementblock
End Sub End Sub

The words Sub and End Submark the beginning and end of the procedure. The words
followin g Sub are the procedure's name, and statementblock is the code you want exec uted
when the event occurs. For exampl e, the following procedure is invoked when the user
clicks the control named Command 1:
Sub Co mm and l _Click ()
Commandl.Height = Commandl.Height + 100 -
Commandl . Wid t h = Commandl.Width + 100
End Sub

Similarly , th e following proced ure is invoked when th e user c licks a form:


Sub Form_Click ()
BackColor = 255
End Sub

Microsoft Visual Basic Programmer's Guide


68 Part 2 Vis ua l Basic Essentials

lmportant If you change the name of a control after attaching a procedure to it, yo u also mu st change
th e name of the procedure, to match the new nam e of the co ntrol. Otherwise, Visual Basic
won' t be able to match the control to the proced ure. When a procedure name does not match
a co ntro l name, it becomes a general procedure: In the Code window, select "(general)"
from the Object box, then select the procedure name from th e Procedure box .

Vi sual Basic recognizes numerous events, each of whi c h has a particular use . For
ex planations of ali events, see the Language Reference, or:

m Search Help for:


events
. . See Tutorial Lesson:
. . "Working with Visual Basic "

Using the Code Window


The Code wi ndow is where you write, di splay, and edit Visual Basic code. It helps you
attac h code to form s and controls by automati call y generating templates for event
proced ures . The templates follow the naming convention mentioned in the prev ious section.
When you first start using Visual Basic, you may just wan t to see code written by someone
else, such as the code in the sampl e application s shipped with Visual Basic. You can use the
Code window to view ex isting codeas we ll as to write new code.
You can open a different Code window for each form and module in yo ur project, and copy
and paste code between them .

To open the Code window:


• Double-click a form or control.
(To open a new form, choose New Form from th e File menu . To open an existin g form ,
doubl e-c li ck the form icon in the Proj ec t window.)
- Or -
• From the Code menu , choose Vi ew Code.

The Code window has three primary parts: two drop-down list boxes and an editing area.
The Object box , on the left, lists "general ," the names of ali the controls on the form , and
"form. " (Yo u' II leam more about "general" later.)
The Procedure box, on the right, li sts all of the eve nts recogni zed by the fo rm or control
selected in the Object box . If you have airead y written a procedure for an even t, the Object
bo x di spl ays th e event in a bold font. Wh en you se lect an eve nt in the Procedure box, the
procedure assoc iated with it (ora code template) is di spl ayed in the editin g area in the
bottom part of the Code window .

Microsoft Visual Ba sic Programmer 's Guide


Chapter 8 Attaching Code 69

To attach code to a form or control:


1 Double-click the control or a blank part of the form.
The Code window opens, or moves to the front. If you double-clicked a blank part of the
form, the Object box displays the name of the form. If you double-clicked a control , the
Object box displ ays the name of the control.
The Procedure box di splays a default event for the form or control (usually the Click
event), or the most recently selected event. If a procedure already exists for that event,
the event name is displayed in a bold font.
The procedure associated with the selected event is displayed in the Code window. If you
want to see procedures associated with another object, continue with Step 2. lf yo u want
to see a different procedure for the selected object, skip to Step 3.
2 In the Obj ect box , selec t an object, as shown in Figure 8.2.

Microsoft Visual Basic [design)


file .!;dit ~ ode Bun ~indow _tl_elp
ICt1N ame 1800. 2 760 J;G2535
1 X 375

lnve stment Calculator

I
· · : Starting Balance

· : : lnterest Rate in ~
_

~---
. ' •
~ ----S ub Cal Endlext
: : : Duration in Years Form
End Sub Labell
~ ---- Label2
Label3
Label4
Rate Text
Startl e xt
· · : Ending Balance Yearslext

+
+

Open the Co de window by double -clicking Select an objec t in


a con trol ar a blank part of the form. the Object box.
Figure 8.2 Selecting an object in the Code window

Microsoft Visual Basic Programmer's Guide


70 Part 2 Vi sua l Basic Ess enti als

3 In the Procedure box, selec t an event, as shown in Figure 8.3 .


The procedure assoc iated with the selected eve nt is di splayed in the Code window. If
there is no procedure, the Code win dow di splays a templ ate to help you write one. The
templ ate includes the first and last lines of the procedure.

Select an event in the Procedure box.

Micro s oft Vi s ual Ba s ic [de s ign)


f il e f dil .Cod e Bun Y:!'.ind ow · tle lp
l c ttN ame 1800. 2760

lnve s lm e nt Ca lcul ato r

: : : lnte,est Ra te in %

~ - --I Sub CalcC md_ Clic k () D1agD1op


D1agOve1
: . . D ur ation in Y ears
En d Su b GotFocus
' - - - --1 KeyDown
KeyP,ess
Compute Endin KeyUp
LoslFocus

Ending Bala nce

. +

The se/ected procedure, ar a


template, is displayed here.
Figure 8.3 Selecting the CalcCmd_Cl ick proc edure

4 Enter the code yo u want in the te mplate, or edit th e existing code .


As you enter code in the Code window, you can use the standard Windows editing
commands: double-click a word or drag to selec t it, press BACKSPACE to delete th e selec ti on,
and so on. For more inform ation :

m Search Help for:


enter cod e

Microsoft Visual Basic Programmer's Guide


Chapter 8 Attaching Code 71

In addition to helping you write an event procedure by providing a template, Visual Basic
also catches errors in the code you type. This feature is call ed syntax checking. You can turn
it on and off from the Code menu. When syntax checking is on, Visual Basic displays a
message when it detects an error in syntax in a line of code. The message tells you what kind
of error yo u' ve made. For Help on correcting the error, press Fl .

Note You' 11 also use the Code window to write general procedures, and code that' s stored
in a module. For information on using modules, see Chapter 15 , "Creating Multiple-Form
Applications." For information on general procedures, see Chapter 9, "Language Elements ,"
or:

m Search Help for:


general
N
111
See Tutorial Lesson:
"Working with Visual Basic"

Attaching Code to a Command Button


To practice using the Code window, attach an event procedure to the command button in the
Investment Calculator you built in previous chapters. You' 11 follow the same general steps
whcnever you attach code to a forro or control. The name of the command button is
CalcCmd. The event that you want it to respond to is Click.

To write the CalcCmd_Click event procedure:


1 Double-click the command button .
The Code window opens and the Object box displays the name you set for the control ,
"CalcCmd." The Procedure box displays the events recognized by the CalcCmd
command button.
2 Select Click from the Procedure box if it is not already selected.
A template for the CalcCmd_Click procedure is displayed in the Code window .
3 Enter the following lines of code between the two lines of the CalcCmd_Click template.
The code will be explained in the next section. (This code assumes you used the control
names and variable names suggested in Chapter 7, "Setting Properties." If you used other
names, be sure to substitute them for the names shown below .)
StartBal = Val(StartText.Text)
Rate = Val(Rat eText.Text)
Years = Val(YearsText.Text)
EndBal = StartBa l * ( 1 + Rate .' 36500) " (Year s * 365)
EndText.Text = FormaU(EndBal. "ff,#INt.fNt0 .00")
4 To save your work, choose Save File from the File menu .

Microsoft Visual Basic Programmer's Guide


72 Part 2 Visual Basic Essentials

lmportant Files saved with the Save File command store both the form and code attached to the form in
binary format. You cannot load this formal into a text editor. To save the code-but not the
form - in text (ASCTI) format , choose the Save Text command from the Code menu .

The completed event procedure should }ook like the code in Figure 8.4.

Objecl: ICalcCmd

Sub CalcCrod Click () •


StartBal = Ual( Start lext .Text )
Rate = Ual(RateText.Text)
Years = Ual(Year sText .Text)
EndBal = StartBal * (1 + Rate / 36500) A (Years * 365)
EndText.Text = ForroatS(EndBal, "11 , 111111,11110.00")
End Su b


+ +

Figure 8.4 Event procedure in the Code window

The statements between Sub andEnd Sub are indented to make the procedure easier to
read . You don ' t have to indent lines in your code.

Note The procedures you attach to forms and controls are part of the form file. Thus, to
permanently save your work on the procedure, you must save the form file to disk. To save
your work and continue , choose Save File from the File menu .

Microsoft Visual Basic Programmer's Guide


Chapter 8 Attaching Code 73

Running the lnvestment Calculator


If you've completed the tasks outlined in this and the previous two chapters , you sho uld
have a working investment calculator.

To run the lnvestment Calculator:


• From the Run menu , choose Start.
- Or -
• Press FS.

To use the lnvestmen t Ca lcu lator, first enter numbers in the first three text boxes. (Yo u can
enter decimal point s. but not dallar signs or commas.) Click the command button to find th e
ending balance of an investment that is compounded daily . Type new values and cli ck the
button again for each new calc ulation . When you ' re finished, choose End from the Run
menu .
If Vi sual Basic detec ts a run -tim e error in your code, it displays an error message. For Help
in resolving the eJTor, press FI.
When you run your app li ca tion , the Immediate window opens undemeath the application
window. (In Chapter 16. "Debugging," yo u' ll learn how to use the Immediate window
to execute individual lines of code and to modify or examine variable values) . It also is
useful during debugg ing- fixing errors in your code. For information on debuggin g, see
Chapter 16, or:

m Search Help for:


debug

To learn how to run th e I nves trnent Calculator as a separate application, without Vi sual
Basic , see the secti on "C reating an Executable Fil e" later in thi s chapter.

Microsoft Visual Basic Programmer's Guide


74 Part 2 Visual Basic Essentials

How the Code Works


Now let's examine th e code in tbe eve nt proced ure; you' ll use similar code in many of th e
applications you write.
Th e CalcCmd_Click eve nt procedure :
1. Retrieves the tex t that the user types in the text boxes .
2 . Converts that text to numbers th at can be used in calculations.
3. Calculates the endin g balance .
4. Formats the endin g balance and displays it in tb e E ndin g B alance text box .

Retrieving Data from the Text Box


The code fo r the Investment Calc ul ator is much easier to write if you work with intermediate
values. For thi purpose, the code inclu des va ri ables. A variable is a place to hold data that
can change as the app li ca ti on run s.
Th e contents of eac h tex t box are represented by the Text property. Yo u refer to a property
with thi s sy ntax:
objectname.propertyname

Tberefore, the followin g statement copies the contents of the StartText tex t box into a
varia ble call ed My Stri n g $:
My Str ing$ - StartText.Text.

Converting Text to Numbers


Computers make a di stin ctio n betwee n data that is stored as text (string data) and d ata th at is
stored as num eri c data. Th e s ig nifi cance here is that tex t in the text box is stored as string
data, and Visual Bas ic cann ot add, s ubtract, or multipl y string data. Consequently , yo u mu st
co nvert th e tex t in a tex t box to a number before yo u can use it in calc ul ation s.
T o convert strin g data to nume ri c data , use the Val fun cti on.
StartBal = Val(StartText.Text)

The Val function con ve rts th e tex t th at fo ll ows it in parentheses into a number. In thi s
exampl e , the express io n in parentheses represents th e tex t in th e StartText tex t box , while
th e nam e on the le ft is the name of a variable th at will be used later in a calc ulation .
For more inform ation o n data types, see C hapter 9 , "L anguage E leme nts," or:

m Search Help for:


data type

Microsoft Visual Basic Programmer's Guide


Chapter 8 Attaching Code 75

Doing Calculations
Mathematical fo rmulas in Visual Basic look m uch like they do on paper, except fo r sorne of
the sym bols called operators. The asterisk (*) means " multiply ," the fo rward slash (/) means
"di vide," and the caret (") means "rai se to the power of."
Pare ntheses are used to make the order of calcul ati on expli cit. For instance, in the followin g
example, the expression 1 + Ra t e / 365 0 0 is evaluated first and then raised to the power
of Ye a rs * 36 5 and fi nally, multiplied by Sta rtBa 1.
EndBal = StartBal * ( 1 + Rate / 36500) A (Years * 365)

T he fo mrnl a is the standard formul a for calcul atin g interest co mpounded dail y.

Formatting Output
T he numeric res ul t of the calculati o n abo ve was ass igned to the vari abl e En d Ba 1 . But befo re
the CalcCmd_Click procedure can di splay th e endin g balance in a tex t box , you mu st
convert the balance back to a string data type.
The easies t way to do thi s is to use the Str$ functi on. The Str$ fun cti on is the opposite of
the Val fu ncti on: lt con verts a number in to its tex t eq uivalent. To assign the result of the
End Bal calcul ation to the EndText tex t box, use th e code below. Note that instead of
ass igning the result to a variable, th e state me nt assigns it to the Tex t property of the E ndTex t
tex t box .
EndTe xt. Text = St r $(E ndBal)

T he Str$ fu nc ti on returns an unformatted string. If yo u use it, the ending balance will be
di splayed as a 15-digit number and you ' ll have many more decimal places than you need .
To format the string so that it di spl ays onl y two dec imal places, use the Format$ fun cti o n.
Like Str$, Format$ converts a number to a stri ng, bu t it also fo rmats it accordin g to the
pattern yo u spec ify, as shown in thi s code:
End Text.Tex t = Fo r mat $( EndBal. "#,###.##0 . 00 " )

T he # sig ns represent the digits greater than l O. T he ones and decimal places are represented
by zeros .
T he Format$ functi on can also spec ify many o th er formats. For compl ete info rmati on on
Format$, see th e Language Ref erence, or:

m Search Help for:


Format$

Now yo u' ve hada very brief introducti on to writin g event procedures. Chapter 9, " Lang uage
Elemen ts," teac hes yo u more about contro l properti es, vari ables, ass ignment statements, data
types. and oth er face ts of the Vi sual Basic lang uage. Chapter 9 also te ll s you how to t1 se a
Vi s ual Bas ic co ntrol stru cture to add more f un cti o nalit y to the In ves tment Calcul ator.

Microsoft Visual Basic Prog rammer 's Guide


76 Part 2 Visual Basic Essentials

Creating an Executable File


To run your application under Microsoft Windows or Presentation Manager outside Visual
Basic, you create an executable file . If you distribute the file to others, they will need a copy
of the Visual Basic run -time fi le (VBRUN l00.DLL) that is in the VB directory. No
additional license or payment to Microsoft is necessary to distribute copies of the run -time
file :

To create an executable file:


1 Open the project that contains the appl ication.
If the project is airead y open , save any changes.
2 From the File menu , choose Make EXE Fi le.
3 Type a filename in the text box.
Your filename automatica ll y replaces the default filename when you start typ in g. Visual
Basic automatically add s the extension .EXE, which you must retain in your filenam e.
4 Choose OK.

Once you've converted yo ur application toan executable file, you can run the exec utable file
from DOS by typing :
win filename

Note If you develop an app li ca ti on using Visual Basic for Windows, that app li ca ti on can
run only under Windows 3.0 or higher, in sta ndard or enhanced mode. Similarly , if you
develop an application using Visual Basic for Presentation Manager, that application can run
only under Presentation Manager.·

For more information on th e op ti ons that are possible when you create an exec utabl e file :

m Search Help for:


executable

Microsoft Visual Basic Programmer's Guide


3 . ·,.,

rA.pplication-Building Techniques

Part 3 surveys basic techniques for writing code for a Visual Basic
application - how to create menus and commands, get input, display results,
draw pictures, and display multiple forms. After reading this part, you should
have a good grasp of how to get things done in Visual Basic. Part 4 shows
you how to add the extra touches included in a sophisticated application .
Language Elements

The Vi sual Basic programmin g lan guage is designed to be flexible and powerfu l, yet easy .
to use. This c hapter ex plain s sorne mechanics of the language so that yo u can use it in your
applications to make decisions, perform calc ul ation s, and subdivide tasks for easier
programm ,ng.
The Vi sual Bas ic language is close in most respects to Microsoft QuickB as ic and the Basic
Professiona l Development System. lf yo u' re fam iliar with these other two modern vers ions
of Basic. the first sect io n of thi s chapter was written espec ially for you.
Online He lp and the Language Refe rence each provide a complete refere nce to the Vi sual
Basic lang uage, includi ng functi ons, statemen ts, and methods. They also in cl ude re ferenc e
informati on o n objec ts, eve nt s, and controls. But this chapter introduces so rn e lang uage
informati on you · 11 need to know to fo ll ow th e rest of the manual.
The mai n sec ti ons in thi s chapter are :
• Mi crosoft QuickBasic and Vi sual Bas ic
• Sorne Mechani cs (Com me nts, um bers, Statements)
• Setting and Rctriev in g Properties and Sto rin g Data
·Vi ual Basic Va ,i ables

• Control S truc tures


• Sub and Fu nc ti on Procedures
80 Part 3 Application -Building Techniques

Microsoft QuickBasic and Visual Basic


l f you're new to Basic or have programmed on ly in BASICA or GW-BASIC, you should
read th is chapter (althou gh programmers experienced in Cor Pascal can skim it).
If yo u' ve alread y used M icrosoft Qu ickBasic , you can skip most of thi s chapter. Visual
Basic adopts the control structures, data types. and most of the sy ntax rules of other form s of
Mi crosoft Basic. H owever, there are a few key differe nces, so yo u may need toread spec ific
sec ti ons of thi s chapter:
• Scope of vari ables works different ly in Vi . ual Basic. Scope deals with how mu ch of the
application recogni zes the vari abl e . The V isual Basic scoping system is both simple and
flexi bl e. If use of local variables (the default) is adeq uate, yo u can skip thi s subj ect for
now. 0therwi se, consult th e sec ti o n "Scope of Vari ables" in thi s chapter.
• Vari ables of the Currency data ty pe con tai n frac ti o nal qu antities, but avoid the roundin g
errors of fl oatin g-point numbers. For more informati on, see the sec ti on " Data T ypes"
later in thi s ch apter.
• Call s to Function procedures mu st incl ude pare ntheses, eve n when there are no
argume nts. A n argument is a constan! ora va riab le passed to or fro m a procedure.

There are other di fferences between V isual Basic and QuickBas ic as well -especi all y
w hen it comes to which statements each support s. For a co mpl ete di scussion of ali the
differences, see Appendix A , "Adapting Bas ic Code."

Sorne Mechanics (Comments, Numbers, Statements)


As you read through the examples in thi s manu al, you ' ll often come across the comment
sy mbol (' ). This symbol tells Vi sual Bas ic no t to do anythin g with the words th at fo llow it.
S uch words are remarks placed in the code for the benefit of yo u, the developer, and oth er
programmers who mi ght examin e the code lat e r. For exampl e:
' This i s a co mment beginning at lef t edge of the sc reen.
Textl . Text = "H i ! " ' Plac e fri endly gree ti ng in text box.

Another thin g you ' ll see a lot of is nu mbe rs . Mos t nu mbers in thi s manu al are decimal (base
l O). But occasionally it's con ve ni ent to use hexadec imal numbe rs (base 16). Visual Bas ic
represents numbers in hexadecimal w ith th e prefix &H and octal (base 8) w ith &O. T he
fo ll ow ing table sho ws the same numbers in dec ima l, oc tal, and hexadec imal.
Decimal Octal Hexadecimal
9 &0 11 &H9
15 &01 7 &HF
16 &0 20 &HI 0
20 &024 &H l4
255 &0377 &HFF

Microsoft Visual Basic Progra mmer's Guide


Chapter 9 Lan guage Ele ments 81

Although sorne important constants are defi ned in hexadec imal, yo u generall y don ' t have to
leam the hexadecimal or oc tal number system yourself. A constan/ is a value th at cannot
change during program executi on.

Note If you want to use a hexadeci m al or octal constant in situati ons that involve large
numbers, append an ampersand (&) to the constant. Thi s causes the value to be stored
correctly as a lon g integer. T he " Data Types" section later in thi s chapter gives more
informati on on lon g integers.

Visual Basic statements are normally one to a line, and there is no statement terminator.
However, you can pl ace more th an one statement on a line by using a colon (: ) to separate
them:
Textl. Text = "Hel lo " : Red = 255 : Textl. BackCol or = Red

Setting and Retrieving Properties and Storing Data


Probabl y the most comm on statement in Vi sual Bas ic is the assignment statement , which
ass igns a value to a vari ab le or to a property reference by copying data from one place to
another. T he sy ntax uses an equ al sign (=):
destination = source
The statement te ll s the applicati on "Copy informati on fro m source to destination." The
destination mu st be a variab le or reference to a property . The source can be any valid Vi sual
Basic expression and may in vo lve calc ul ati ons.
Assignment statements in Visual B asic generally do one of three things:
• Set the value of a property
• Retrieve th e value of a property
• Store data in a variab le

Setting the Value of a Property


In earlier chapters yo u learned how to set properties at design time with the Properti es bar.
T o set the value of a prope rty at run time, pl ace a refere nce to the property (object.prop erty)
on the left side of an ass ignment statement. For exampl e:
Textl . Text - " Your name here ."
Textl.Text = Str$(Amount)
Textl. Text = " Th e amount is " + Str$ ( Amount)

The Text property is a strin g of characters th at spec ifies the contents of a text box, li st box,
or co mbo box . You ca n ass ign onl y strings to thi s property. T he last two statements above
use the Str$ fun cti on to co nve rt a number to a strin g. V isual Basic requires th at both sides o f
the ass ignme nt stateme nt be strings or both be numeric.

Microsoft Visual Basic Programmer's Guide


82 Part 3 Application-Building Techniques

Retrieving the Value of a Property


To retrieve the value of a property and store it in a variable, place a reference to the property
on the right side of an assignment statement. For example:
MyString$ - Textl.Text
Amount - Val (Textl.Text)

The second statement uses the Val function to convert a strin g into a number. This function
is the converse of the Str$ function .

Storing Data in a Variable


You also can use assignment statements to perform calcu lations and assign the result to a
variable:
Ergs = 10
Ergs = Mass * (Velocity A 2) ' Erg s = matter t imes velocity sq uared.
Ergs - Ergs + 1

Visual Basic Variables


A variable holds a specific piece of informa ti on needed by your application. Each variable
has severa! important attri butes, including :
• Name. This is the word you use to refer to the variable.
• Data type. The data type determines what kind of information the variable can store.

In addition, each variable has a scope th at determines how much of the application
recognizes the variable. For more information on scope, see the next section, "Scope of
Variables."

Variable Names
A variable name can be up to 40 characters long, and ca n include letters, numbers, and
underscores ( _ ). There are two restrictions :
• The first character in the name must be a Jetter.
• You cannot use a reserved word as a variab le name, thou gh yo u can embed one inside a
larger variabl e name (for example, PrintThis) . Reserved words are words that have a
special meaning in Visual Basic. This inc ludes predefined statements, function s,
methods, operators (such as And or Mod) , and property narn es .

In addition to numbers and letters, a variab le narne also can include a si ngle type-declaration
character used as a suffix, as explained in the next section .

Microsoft Visual Basic Programmer's Guide


Chapter 9 Language Elements 83

Data Types
Visual Basic variables come in six standard types, as shown in Table 9. 1.
Table 9.1 Standard Variable Types
Type-declaration
Type name Description character Range
lnteger Two-byte integer o/o - 32,768 to 32,767
Long Four-byte integer & - 2,147,483,648 to
2,147,483,647
Single Four-byte floatin g- - 3.37E+38 to
(the default) point number 3.37E+38
Double Eight-byte floating- # (or none) - 1.67D+308 to
point number l.67D+308
Currency Number with fix ed @ - 9.22E+l4 to
decimal point 9.22E+ l4
String String of characters $ (not applicable)

Befare using a variable, you should decl are its data type with the Dim statement (or one of
the keywords Global or Static). For example, the following statements declare an Integer ,
Double, String, and Currency type , res pec tively:
Dim I As Integer
Dim Amt As Double
Dim YourName As String
Dim Bill s Paid As Currency

The Dim statement can combine multiple dec larati ons, as in these statements:
Dim I As Integer, Amt As Doubl e
Dim YourName As String, Bill sPaid As Currency

The third column of Table 9 . 1 lists the Vi s ual Basic type-declaration characters. Instead of
declaring a type with As, you can identify the data type of a variable by appending a type -
declaration character to the end of the variable name . lf you do so, use the type-declaration
character consistently. For example, Co unt% has type Integer, X# has type Double, and
MyName$ has type String.
If you don ' t use either method to declare a type, Vi sual Basic assumes the variable has the
Single data type. However, you can chan ge thi s de fault for a form or module by using a
Deftype statemen t. For more information o n Deftype, see Chapter 17, " Advanced Lan g uage
Features" ; the Language Reference ; or:

m Search Help for:


define type

Microsoft Visual Basic Programmer's Guide


84 Part 3 App lication- Bu ildin g Tech niqu es

If yo u know th at a variable will never need to store a fractional amo unt (such as 3.57) ,
dec lare it as an integer ty pe (lnteger or Long). Operations are fas ter with integers. If the
vari able contains a frac tion , declare it as a flo atin g-point or Currency variable. The
Currency data type supports up to four digits to the right of the decimal point and 14 to the
left. F loating- point numbers have much larger ran ges than Currency, but have a ro unding
erro r produ ced by conversion between base two and base ten fraction s.

Note Floatin g- poi nt constants can be expressed as mmmEeee or mmmDeee, in whi ch mmm
is the mantissa and eee is the exponent (a power of ten). Thus, the hi ghest poss ible va lu e of a
Single data type is 3.37E+38, or 3.37 ti mes 10 to the 38th power. T he use of D causes a
value to be stored as a Double data type.

Values of numeri c vari abl es can be ass igned to each other. Visual Basic round s off th e
frac ti onal part of a fl oatin g-point nu mber before assigning it to an integer.

Scope of Variables
T he scope of a variable is its visibility wi thin an application - in other word s, how rnuc h of
the appli cati o n recogni zes the variable. For example, when different proced ures refer to a
variable coun t , do they all refer to the sam e piece of information, or do th ey eac h have their
own prívate versio n?
T he different levels -from local to global -are summari zed in Figure 9. l.

Global vari ables


(declared in the global module)

Form- level variables Module- leve! variable s


(dec lared in Declarations section) (declared in Declarat ions section )

local local local local local local


variables variables variables variables variab les va ri ab les

procedures procedures
Form Module

Application

Figure 9.1 Vari able leve ls, from loca l to global

Scope is one of the principal areas in whi ch Vi sual Basic differs from o ther vers io ns of
Bas ic, inc ludin g M icrosoft QuickB as ic. With Vi sual Basic, the issue of scope is a litt le
sirnp le r beca use it is determin ed mainl y by the placement of a declarati on.

Mic rosoft Visual Basic Programmer's Guide


Chapter 9 Language Elements 85

Local Variables
A local variable is recogni zed only within the procedure in which it appears. A local
variable is a good choice for any kind of temporary calculation. A dozen procedures can ali
have a variable called Temp , for instance, but as long as Temp is local, each procedure has its
ow n vari able. A procedure can alter its local Temp vari able without affecting Temp variables
in oth er procedures.
T o make a vari able local, place the data declarations (Dim state ments) inside the procedure:
Sub CmdButtonl _Click ()
Oim Centig r ade As Double
Oim Fa hren heit As Doub l e
Centigrade - Val(Readout.Tex t )
Fahren heit = (Centigrade * 1 .8) + 32
Readout.Text - Format$(Fa hrenh eit)
End Sub

A nother way to create a local variable is to just use it without any Dim statement ; Visual
Basic ass um es th e variabl e is local. However, thi s tec hnique is less rel iabl e, as you ' II see in
an upcoming secti on, "Confli cting Scope Declarations."

Form-Level and Module-Level Variables


To share inform ati on between procedures of a form , you create a fo rm -level variable. A
form-level variable is recogni zed by ali the procedures attac hed to a fo rm. You create form -
leve l variabl es by access ing the Declarations sec ti on of form code and e nte1i ng data
dec larati ons th ere. Fo r exampl e:
Oim Wa r pS peed As Si ngle, Ali enC ount As I nt eger

To edit th e Declarations secti on of a form, open the Code window and select "(general)"
from the O bj ec t box and "(declaration s)" from th e Proced ure box .
Mod ul e- leve ! vari abl es are similar to fo rm-level vari ab les. A module- leve/ va riable is
dec lared in the Dec larati ons section of a module and is shared by ali the procedures in that
modu le.
A noth er important reaso n fo r using form -leve l or modul e- level variabl es is th at th ey persist
after a procedure return s. Unl ess explicitl y declared as Static , a local vari able las ts as long
as the procedure does. Wh en the procedure is called again, th e variable starts at 0 - or an
empty string, if th e vari able is a strin g. The value of a form-level variable is more
perm ane nt, and las ts as long as the form does .

Global Variables
Global va riables have the broadest scope of ali. The entire appli ca ti on has access to a global
va ri able. T hey also are th e mos t persiste nt vari ables, re taining the ir va lues th roughout the
e nti re appli cati on.

Microsoft Visua l Basic Programmer's Guide


86 Part 3 Application-Building Techniques

You define global variabl es by decl arin g them in the global module and by using the Global
statement instead of the Dim stateme nt :
Global Warp Speed As Sin gle , Ali enCo unt As Integer

Conflicting Scope Declarations


Typicall y, you declare a vari abl e in o nly o ne place. But you can reuse a variable name at
different levels. For example, you can declare a variable named Ali enCount both inside a
procedure (creating a local vari able) and at the form level.
When you declare a variabl e at both the procedure and form level, a statement always refers
to the variable at the nearest leve! of scope. This means that references to Al i en Co un t
inside the procedure affect onl y th e local variable named Ali enCount . The form -leve l
version of Ali enCount is a se parate variable. You cannot refer to the form-level variabl e as
long as there is a local vari able by -the same name .
Jf a vari able appears in a procedure witho ut a declaration, it is local by default. But Vi sual
Bas ic won' t advi se you wheth er it is dec lared ata higher leve] or not. If you want to make
sure that a variable is local , it 's best to ex plicitly declare it.

Control Structures
The statements that control dec isions and loops in Visual Basic are called control structures.
Visual Basic control structures are identi caI to those in recent versions of Microsoft Basic ,
and are similar to the control stru c tures found in C and Pascal. This section introduces the
most commonly used contro l stru ct ures:
• If... Then blocks
• If... Then ... Else blocks
• Select Case statements
• Do loo ps
• For loops

Note The term "control struc tures'· has nothing to do with controls on a form .

The first three items above are dec ision structures. You use them to define groups of
statements that may or may not be executed, depending on run-time conditions. The las t tw o
ítem. are loop structures. Yo u use th em to defin e groups of statements that Vi sual Basic
cxec utes repeatedly.

Microsoft Visual Basic Pro grammer's Guide


Chapter 9 Language Elements 87

lf ... Then Blocks


Use an If... Then block to execute one or more statements conditionally. You can use one of
two different forms of sy ntax:
If condition Then statements

If condition Then
statements
End If

If condition is true, Visual Basic executes al! of the statements. (The statements consist of
zero or more lines of code.) You can use an If... Then block to execute just one statement
conditionally:
If X > 0 Then Textl . Text - "X is greater than zero. "

If X> 0 Then
Textl.Text "X is greater than zero."
End If

Or, as shown in the next example, you can place more than one statement in an If... Then
block. The example builds on the Investment Calc ulator presented in Part 2. This variation
computes the starting balance necessary to reach an ending balance entered by the user:
If StartBal - 0 Then
StartBal = EndBal / (1 + Rate / 36500 ) A (Years * 365)
StartText.Text - Format$(Start8al l
End If

The condition is a Boolean expression. A Boolean expression is one that can be evaluated as
true or false. Often condition is a relationaJ test such as X > O or X = Y. Relational tests use
the following operators.
Operator Meaning
= Equal
<> Not eq ual
< Less than
<= Less than or equa l to
> Greater than
>= Greater than or equal to

The relational operators work with both strings and numbers. You can test string variables
and constants for equality :
If AdrVar$ = "123 Main Street" Then

Microsoft Visual Basic Programmer's Guide


88 Part 3 App lication -Build ing Te chniq ues

You also can perform greater-than and less-t han tests with string vari ables. Visual Basic
resolves these kinds of comparisons by using alphabetical arder, so that Aardvark < Zy pher
evaluates to tru e. However, you cann ot compare a strin g to a number.
The keywords And , Or, Xor, Eqv, Imp, and ot canjoin conditions together to create
comp lex conditions. For exampl e:
If . (X > Y) Or (X> = 10 And X <- 20) Then

Sorne properties are Boolean-they have on ly two settings: True or False. A reference to a
Boolean prope rty can, by itself, prov ide the co nditi onal part of an If statement.

lf ... Then ... Else Blocks


Use an If... Then ... Else block to define severa! blocks of state ments, of whi ch one bl ock
gets exec uted:
lf conditionl Then
statementblock- 1
[ Elself condition2 Then
statementblock-2 ]
[Else
statementblock-n ]
End If

Visual Basic firs t tests conditionl. If it's false, Visual Basic proceeds to test condition2 , and
so on , until it fi nds a tru e cond ition. The corresponding statement bl ock is then executed.
You can opti onall y include an Else state ment block, which Visual Bas ic exec utes if none of
th e condi ti ons is true.
lf... Then is reall y j ust a special case of If...Then .. . Else. Note th at you can have any
number of Elself clauses, or none at ali. You can include an Else clause wheth er or not you
have Elself clauses .

Microsoft Visu al Basic Programmer's Guide


Chapter 9 Language Elements 89

The following procedure uses an If... Then ... Else block to make the lnvestment Calculator
(shown in Part 2) more flexible. This version lets the user calculate any of four different
va lues: Starting Balance, Interest Rate, Duration in Years, or Ending Balance. The
If... Then ... Else block performs a series of tests to see which value was set to zero. The
procedure then recalculates that value, using the other three values as input:
Sub CalcCmd_Click ()
StartBa l = Val(StartTe xt .Text)
Rate = Val(RateText.Text)
Yea rs = Val ( Yea rsText. Text)
EndBal ~ Val(EndT ext.Text)

If StartBal = 0 Then
StartBal = EndBal / (1 + Rate / 36500) (Years * 365)
A

StartText.Text = Form at $(StartBal)


Elself Rate = 0 Then
Rate = ((EndBal / StartBal) (1 / (Years * 365)) - 1) * 36500
A

RateText.Text = Format$(Rate)
Elself Years = 0 Then
R = 1 + Rate / 36500
Years = (Log(EndBal / StartBal) / (Log(R)) / 365)
YearsText.Text = Str$(Years)
Else
EndBal = StartBal * (1 + Rate / 36500) (Years * 365)
A

EndText.Text = Format$(EndBal)
End I f
End Sub

This procedure uses a local variable, R to si mplify the calculation of Ye ar sR is local anda
double-precision type by default, so the example works correctly as long as R is not declared
at some other leve! (form or global) .

Microsoft Visual Basic Programmer's Guide


90 Part 3 Application -Bui lding Techniques

Select Case Statements


Use a Select Case statement to take different actions depending on the value of a particular
variable. A Select Case statement provides sorne of the same capability you get with an
If... Then ... Else statement, but it makes code more efficient and readable.
For exampl e, you can use an If... Then ... Else statement to repeatedly test a value until a
match is fo und . Yo u have a numeric variable X, for instan ce, and want to take one set of
ac tions if X is egu a] to 1, another set of actions if X is egual to 2, and so on. The fo ll owing
statements di splay a string in•a text box according to the value of X:
If X= 1 Then
Textl. Text = " One "
Elseif X= 2 Then
Textl.Text = "Two"
Elself X= 3 Then
Textl. Text "Thr ee "
El se
Textl.Text "Too big"
End I f

Thi s code stores "One" in the text box if X is 1, "Two" in the text box if Xis 2, and so on.
The following Select Case statement performs exactly the same operation :
Select Case X
Case 1
Textl. Text "One"
Case 2
Textl. Text "Two "
Case 3
Textl. Text "T hree "
Case Else
Textl . Text "Too bi g"
End Select

This vers ion of the code is easier to read, and Visual Basic exec utes it slightl y fas te r.
However, not al] If ... Then ... Else statements can be rewritten thi s way.
A Select Case state ment works with a single test value (w hich can be num eric or string) .
Visual Basic tes ts to see if any value in expressionlist is egu a] to the test value . lf so, it
exec utes th e corres ponding block of statements. Select Case uses thi s sy ntax:
Select Case rextexp ression
Case expressionlist 1
statementblock- 1
[ Case expressionlist2
starementblock -2]
[ Case Else
srorem enthlock- 11 ]
End Select

Microso ft Visu al Basic Programmer's Guide


Chapter 9 Language Elements 91

Each expressionlist is a list of one or more numeric or string values. If there is more than one
value in a single list, the values are separated by commas. Each statementblock contains zero
or more statements. Visual Basic executes statements in the Case Else clause (which is
optional) if none of the values in the expression lists matched the test value.

Do Loops
Use a Do loop to execute a block of statements an indefinite number of times. There are
several variations of the Do ... Loop statement, but each of them checks a Boolean condition
to determine whether to continue execution .
The following Do ... Loop says, "as lon g as the condition is true, execute the statements":
Do While condition
statements
Loop

When Visual Basic executes this Do loop, it first tests condition. If condition is false, it skips
past all the statements. If true, Vis ual Basic :
1. Executes the statements.
2. Goes back to the Do While statement and tests the condition again.

Consequently, the loop can be executed any number of times, as long as condition is true.
Note that the statements are never executed if the condition is initially false. (This version of
Do ... Loop is equivalent to While ... Wend, which Visual Basic also supports.)
For example, the follow ing Form_Click procedure prints numbers from I to 20. The Print
method (which prints to the form unl ess anot her object is specified) is given only once.
Visual Basic executes the stateme nt Pri nt I as long as I is less than or egua! to 20:
Sub Form_Clic k ()
Dim I As Integ er
I = 1
Do While I <= 20
Print I
I = I + 1
Loop
End Sub

Another variation of the Do ... Loop statement executes the statements first , then tests
condition after each execution. Thi s variation guarantees at least one execution of
statements:
Do
statements
Loop While condition

Two other variations are analogo us to the previous two, excep t that th ey test whether
condition is false rather than true :

Microsoft Visual Basic Programmer's Guide


92 Part 3 Application -Building Techniques

Do Until condition
statements
Loop

Do
statements
Lo5>p Until condition

Note that Do Until condition is exactly equivalent to Do While Not condition.

For Loops
Use a For loop to execute a block of statements a set number of times. Unlike a Do loop, a
For loop inc ludes a spec ial variable called counter, which increases (or decreases) in value
during each repetiti on of the loop . The sy ntax is:
For counter = start To end [Step increment]
statements
Next [counter]

The arguments counter, start, end, and incrementare al] numeric . They are not required to
be integers, but Vi sual Basic 's performance is better if they are.

Note The argument increment can be either positive or negative. If increment is positive,
start must be less than or eg ua! to end . lf increment is negati ve, start must be greater than or
equ a l to end.

In executing the For loop, Visual Basic:


1. Sets counter equa l to start.
2. Tests to see if counter is greater than end. If so, Visual Basic ex its the loop. (If increment
is negat ive, thi s ste p tests to see if counter is less than ene/. )
3. Executes th e statements .
4. Increments coun ter by 1- or by increment if it is spec ified . Then, Vi sual Basic goes
back to Step 2.

For example, the folJowing procedure performs the same action s as the Do loop in the last
sec tion , but with fewer statements:
Su b Form_Click ()
Dim I As Integer
Far I = 1 To 20
Print
Next I
End Sub

Microsoft Visual Basic Programmer's Guide


Chapter 9 Language Elements 93

The For loop in this procedure prints all the numbers from 1 to 20. The difference between
this loop and the Do ... While loop of the last section is that the For statement performs the
initialization (1 = 1) and the incrementing (1 = 1 + 1) automatically.
To specify an increment other than 1, use Step. For example, the following code modifies
the procedure above by printing ali odd numbers from 1 to 20:
Sub Form_Click ()
Dim I As Integer
For I = 1 To 20 Step 2
Print I
Next I
End Sub

Sub and Function Procedures


Toe foundation of a Visual Basic application consists of its event procedures. (An event
procedure is the code that is invoked when a forro or control recognizes that a particular
event has occurred.) But you can also create general procedures. A general procedure is not
invoked until another part of the application explicitly calls it.
Why create general procedures? One reason is that severa! different event procedures may
need the same actions perforrned. A good programming strategy is to put common
statements in a separate procedure (a general procedure), and have event procedures call it.
This eliminates the need to duplicate code and also makes the application easier to maintain .
Figure 9.2 illustrates the use of a general procedure.

Change event • Textl _Change


• -------- - ----- --- - -- - ----,
''
retum
''
'' ,,
Click event • Cmdl - Click
¡.---;~.~~;---_
. Display BarChart

r
1

Click event • Cmd2_Click • --- -- -- -- -- ---- ---- -- ___ ____ ;


~------~- I retum

Event procedures General procedure


containing common code

Figure 9.2 How genera l procedures are called by event procedures

Microsoft Visual Basic Programmer's Guide


94 Part 3 App\i cation- Build ing Techniques

In essence, a ge neral procedure tells the application how to perform a specific task. Once the
procedure is defi ned , you can cal! it from anywhere in the application. For exa mpl e, a
complex procedure could di splay a bar chart. After writing the procedure, you can then
di splay a bar chart with a single statement:
Di sp l ayBarChar

T he use of ge neral procedures also helps divide complex application code into manageable
units.
Procedures ca n e ither be Sub procedures or Function procedures. A call to a Sub proced ure
is a complete statement, whereas a cal] to a Function procedure is part of an express ion. For
example, the fo ll owing statement shows calls to two different Function procedures:
Sum = CrossProduct(A, B. C) + St andDe v(Arrl , N)

Cr oss P rod u et and Stand Dev each retum a single value, which Visual Basic the n uses to
calcu1ate the va lue of Sum .

Note Even t proced ures are alw ays Sub procedures, never Function procedures.

Scoping and Creating Procedures


Procedures ha ve scope, just as variables do. However, the scoping mechani sm for
procedures in vo l ves onl y two rul es :
• Visual Basic reso lves a ca l! to a procedure by first looking in the c un-ent fo rm or modul e.
• [f the proceJure name is no t found , Vis ual Bas ic sca ns a li modules fo r th e procedure .

Consequentl y. proced ures defined in a mod ul e are recognized by th e e ntire app li ca ti on. But
procedures att ached to a fo rm can be cal1ed only by other proced ures attached to th at forrn.
A proced ure name defi ned in a module mu st be unique across ali mod ules. A procedure
na me defined in a form can be defined in other forms . (Thu s, eac h fo rm ca n have its ow n
Form_Load proced ure.)
To create a new general procedure, make sure the Code window is open. Then choose New
Procedure from the Code menu . Another technique is to type a procedure headin g within the
Code window an d press ENTER. T he procedure heading can be as simple as Sub or Function
fo llowed by a name. For exa mpl e, you can enter either of the fo ll owi ng:
Sub Updat eForm
Function GetCoord

Vi sual Bas ic respond s by clea rin g the Code window and displaying a template for the new
procedure .
To ed it an ex istin g ge neral procedure, select "(general)" from th e Objec t box in th e Code
window, th e n se lec t the proced ure in th e Procedure box .

Microsoft Visua l Basic Programmer's Guide


Chapter 9 Language Elements 95

Sub Procedures
The syntax for a Sub procedure is :
Sub procedurename (arglist)
statements
End Sub

The arglist is a list of argument names, separated by commas if there is more than one. Each
argument can optionally have a type-declaration character (%, &, !, #, @, or $)oran As
clause. The syntax of each argument is :
[ByVal] variablename [()] [As type]

The optional ByVal keyword is explained in the section "Passing Arguments by Value" later
in this chapter.
The type can be any of the standard data types: Integer, Long, Single, Double, Currency ,
or String. Parentheses after variablename indicate that the argument is an array. See
Chapter 17, "Advanced Language Features," for more information on arrays, as well as the
special Form and Control argument types.
Each time the procedure is called, the statements between Sub and End Sub are exec uted.
Visual Basic substitutes each reference to an item in the argument list with the correspond-
ing argument. For example, suppose you have defined the MultiBeep procedure as :
Sub MultiBeep (NBeeps As Integer)
Dim I As Integer
For I = 1 To NBeeps
Beep
Next I
End Sub

The following statement calls MultiBeep with the argument 3:


Mult i Beep 3

Visual Basic responds by calling the MultiBeep procedure and passing 3 as the argument.
The procedure substitutes 3 for NBeeps (the name that appears in the argument li st), thus
executing the following code:
Dim I As Integer
For I = 1 To 3
Beep
Next I

The procedure therefore beeps three times. In the next example, the procedure beeps 12
times because 12 is passed as the argument:
Mult iBeep 12

Microsoft Visual Basic Programm er's Guide


Part 3 App lication- Building Techniq ues

Calls to a Visual Basic Sub procedure do not use parentheses around the argum ent li st. For
example, the foll owing procedure uses the Log function (which always uses a base of
2. 71 8282) to calculate logarithms of any base. The logarithm is calculated from the seco nd
and thi rd arguments, and assigned to the first argument:
Sub LogB (Resu l t As Doubl e, Base As Doubl e, X As Double )
Result = Log(X) / Log(Base)
End Sub

Then the following calls to LogB store results in the vari ables Ex ponentl , Log l 0, and
Ye a rs:
LogB Exponentl, B, A
LogB Logl0, 10 , Amt
LogB Years, 1 + Rate / 365 00 , EndB al / Sta r tBa l

The LogB procedure also demonstrates how a procedure can return informati o n by changing
th e value of one or more of its arguments. If you call LogB and pass a vari abl e as the first
argum ent, thi s variable gets changed. Both Sub and Function procedures can change their
arguments thi s way.

Function Procedures
The syn tax for a Function procedure is:
Function p rocedurename (a rguments) [As type]
statements
End Function

Every thing said in the previous section about argum ents applies equ all y to Function
proced ures. Aside fro m th e Function keyword , there are three di fferences betwee n Sub and
Function procedures:
• Yo u use parenth eses with each Function call .
• Function procedures have types, just as vari ables do. Thi s determin es the type of the
re turn value. (In the absence of an As clause, the type is determin ed from the
procedurename , whi ch can have a type-declaration character.)
• Yo u re turn a value by assigning it to the procedurename itself. Whe n the Function
procedure return s a value, thi s value is then used as part of a larger express ion.

T he example at the e nd of th e previous secti on can be rewritten as a Function procedure:


Function LogF ( Base As Double, X As Doub l e) As Doub l e
LogF = Log(X) / Log(Base)
End Function

Microsoft Visual Basic Programmer's Guide


Chapter 9 Language Elements 97

The calls to the LogB procedure can then be rewritten as:


Exponentl = LogF(B. A)
Logl0 = LogF(l0 , Amt)
Years = LogF(l + Rate / 36500, EndBal / StartBal)

The last statement, slightly modified, could form part of the code far the CalcCmd_Click
procedure introduced earlier in this chapter:
Years = LogF(l + Rate / 36500, EndBal / StartBal) / 365

Passing Arguments by Value


To prevent an argument from getting changed, place the By Val keyword in front of the
declaration. Far example, the following procedure alters the first argument but never the
seco nd:
Sub Factorial (Result As Double, ByVal N As Integer)
Result = 1
Do While N > 0
Result = Result * N
N= N- 1
Loop
End Sub

As yo u can see, the procedure does change both arguments, Res u 1 t and N. However,
because of the By Val keyword, changes to the seco nd argumentare ignored once the
procedure retums. The following statement changes the value of Amt (placing the results of
the calculation there) and has no effect on X:
Factori a 1 Amt. X

The first argument gets passed by reference, the Visual Basic default. This gives the
procedure direct access to the argument itself- in this case, Amt. The second argument is
passed by value . This gives the procedure a copy of the value of the argument. The
procedure has no access to the second argument-in this case, X.
You can give a constant ora complex expression asan argument, even if it is passed by
reference (the default). Visual Basic responds by storing the value of the argument in a
temporary variable and then passing the four-byte address of this temporary variable . To
force a si mple variable to be passed this way, place it in parentheses, as in the function call
Log F ( (Base) • ( Amt)). This has the same effect as passing by value.

lmp ortant Property values (such as Textl .Text) cannot be passed directly unless you pass them by
value. Either use a ByVal argument or put parentheses around the property reference.

Microsoft Visual Basic Programmer's Guide


98 Part 3 Application -Building Tec hni ques

Visual Basic Operators


Visual Basic supports a rich set of arithmetic, re!ational, and logical operators, shown in
Table 9.2 according to precedence, from highest to lowest.
Table 9.2 Visual Basic Operators
Type Name of operation Symbol
/1
Arithmeti c Ex ponenti ati on
Negation (additi ve inverse)
Multiplication and division *,/
Integer division \
Modulo arithmetic Mod
Addi tion and subtracti on +, -
Re lati onal Equal, greater than, less than, =, > , < , <>, <=, >=
and so on
Logical (bit-wise) Logical negation Not
And And
Inclusive Or Or
Exc lusive Or (either or but not Xor
both)
Logical eq ui valence Eqv
Implication (first opera nd fa lse lmp
or second operand true)

Precedence determines which operators to appl y fi rst in a complex expression. If you


understand precedence, you are freed fro m relying heav il y on parentheses . For exampl e,
co nsider the foll owing expression:
Var l = Va r 2 An d X+ Y* 2 > Z

Visual Basic evaluates th is expression as if the foll owing parentheses were present:
( Va r l = Var 2) And ((X+ (Y* 2)) > Z)

Sorne ex pressions involve operators at egua! levels of precedence. When thi s happens,
Vi sual Basic operators assoc iate left to right. Howe ver, if an expression contains multiple
cal Is to Function procedures, yo u cannot rely on the m being executed in a parti cul ar order.
T he fo llowing operati ons, whi ch may be new to you, are covered in the nex t few sections:
• Ex ponenti ati on
• lnteger di vision and mod ul o arithmeti c
• Logical operati ons
• String operations

Mic rosoft Visual Basic Programmer's Guide


Chapter 9 Language Elements 99

Exponentiation
Exponentiation is simply raising a number to a power-multiplying the first operand by
itself repeatedly. Far example:
Result Amt 2A ' Amt squared (Amt * Amt).
Result = Amt A 3 ' Amt cubed (Amt * Amt * Amt).
Result Quantity A -2 ' Quantity raised to power of - 2 .

lnteger Division and Modulo Arithmetic


Visual Basic supports two kinds of division. Regular division ( /) uses floating-point
calculations, and retums a floating-point result. Integer division ( \) rounds the operands to
integers, if necessary, and truncates the results .
Because integer division truncates the results, you lose the fractional portian. However, you
can use modulo arithmetic to get the remainder. Far example, the first statement below
obtains a single quotient in floating-point form. The last two statements obtain an integer
quotient and remainder:
Quot ~ 19 / 2
IntQuot = 19 \ 2
Remainder = 19 Mod 2

After these statements are executed, the values of Quot , I ntQuot , andRe ma i nder are 9.5 ,
9, and 1, respectively .

Note Truncation is not the same thing as rounding. Truncation discards the fractional
portian, no matter how large. Rounding adds l to the integer portian of a number if the
fractional portian is greater than or equal to 1/2.

Logical Operations
Logical operators serve a dual purpose. They combine Boolean conditions in a meaningful
way, and they also perform bit-wise operations on any integer values. A bit-wise comparison
is a comparison of corresponding bits in two numeric expressions. A bit is the smallest unit
of data a computer can store.
The use of these operators in Boolean expressions works as long as -1 is used to represent
True and O is used to represent False. Visual Basic relational operators and Boolean
properties always retum True or False according to this convention .
For more information on how each of these operators combines bits:

Search Help for:


111 operator

Microsoft Visual Basic Programm er's Guide


100 Part 3 Application -Building Techniques

String Operations
Visual Basic supports operations on strings only for the plus operator (+ ), which denotes
string concatenation, and the relational operators. The relational operators compare strings
according to alphabetical order.

Microsoft Visual Basic Programm er's Guide


Responding to Commands

Visual Basic provides many ways to put commands in your application. Command buttons,
for example, enable a user to easily perform an action : The user clicks the button and your
code (a Click event procedure) responds.
But as you experiment with Vi sual Basic, yo u'll want to try different ways of providi ng
commands. Menus take up less screen space than command buttons, and are almost as easy
to use. Shortcut and access keys provide command capabilities from the keyboard ; they help
you support users who don ' t have a mouse, and they make it fas ter to execute a command
when the user's hands are at the keyboard .
Thi s chapter expl ains how to put commands in yo ur appli cati on, starting with the simplest
techniques and progressing to techniques that require more programming.
The main sec tions in this chapter are:
• Respondin g to Command Buttons
• Controll ing Command Buttons at Run Time
• Creating a Menu -Dri ven Applicati on
• Controlling Menus at Run Time
• Addin g and Deleting Menu Commands
• Shortcut and Access Keys
• Contro lling the Tab Order
102 Part 3 Application-Building Techniques

Responding to Command Buttons


A command button is a straightforward way to provide a command. You use the Caption
property to display text on the button that tells the user what the button does. For example,
Figure 10.1 shows a command button with the Caption property set to "Start firework s
display ."
11 Test Button aa

iStarl fi,eworks dispfay J

Figure 10.1 Command button with caption

When the user chooses the button, it not only carries out the appropriate action (in this case,
starting fireworks), it also looks as if it ' s being pushed in and released. The latter feature ,
which is built into command buttons, is a visual cue to users that they've successfully
chosen the button .
There are four ways the user can choose a command button:
• Use the mouse to click the button.
• Move the focus to the button by pressing the TAB key, then choose the button by pressing
the SPACEBAR. (Focus is the ability to receive user input typed at the keyboard.)
• If the command button is the default command button for the form , pressing ENTER
chooses the button , no matter which control on the form has the focus.
At design time, you specify a default command button by setting that button's Default
property to True (- 1) .
• If the command button is the default Cancel button for the form , then pressing ESC
chooses the button , no matter which control on the form has the focus.
At design time, you specify a default Cancel button by setting that button ' s Cancel
property to True (- 1).

All these actions cause Visual Basic to invoke the Click event procedure . lt makes no
difference to the application which method is used.

Microsoft Visual Basic Programmer's Guide


Chapter 10 Responding to Commands 103

Picture boxes also recognize the Click event, so you can use a picture box anywhere you'd
use a command button. For instance, instead of the command button shown in Figure 10.1
(which has the caption, "Start fireworks display"), you could use a picture box that displays
a picture of a firecracker. Figure 10.2 shows a picture box that uses one of the firecracker
icons from the Icon Library included with Visual Basic.

al Test Button aa

Figure 10.2 Picture box with icon from the lcon Library

Note Aside from Click, the other events recognized by both command buttons and picture
boxes include DragDrop, Dragüver, KeyDown, KeyPress, KeyUp, GotFocus, and
LostFocus.

For more information on comrnand buttons, see the Language Reference, or:

m Search Help for:


command button

For information on displaying an image in a picture box, see Chapter 13 , "Creating


Graphical Effects" ; the Language Reference; or:

m Search Help for:


picture box a See Tutorial Lesson:
"Creating Custom Applications"

Microsoft Visual Basic Programmer's Guide


104 Part 3 Application-Building Techniques

An Example with Two Command Buttons


The application shown in Figure 10.3 responds to two commands: Clicking the left
command button ("Duplicate") copies text from the top text box to the lower text box.
Clicking the right command button ("Clear Out") clears the text boxes, which are labelled
"Source" and "Destination."

1m Two-Button Example aa
Source

D estination

¡Ouplicate¡ ~
~

Figure 10.3 An application with two command buttons

There are six controls in ali , with the following properties.


Control CtlName property Caption property
Top text box Src
Bottom text box Dest
Top )abe! Source
Bottom !abe! Destination
Left command button Dup Duplicate
Ri ght command button Clearüut Clear Out

This is the Click event procedure for the left command button (named "Dup" in code):
Sub Dup_Click ()
Dest.Text = Src.Text
End Sub

Ali the work of thi s procedure is done in the seco nd line of code. The Text property specifies
the st1ing of tex t displayed in the text box . Thus, the statem en t copies the contents of the text
box named "Src" into the tex t box named "Dest'':
Dest . Text = Src . Text

Mic rosoft Visual Basic Programmer's Guide


Chapter 10 Responding to Commands 105

Clicking the Clear Out command button (referred to as "Clearüut" in code) erases the
contents of the text boxes by placing an empty string in each one. The Clearüut_Click
procedure tells the button how to respond to the click:
Sub Clearüut_Click ()
Dest.Text = ""
Src .Te xt =
End Sub

Translating to Uppercase
By itself, copying text from one location to another isn't that interesting. We can make the
application just described more useful by adding text translation.
Visual Basic includes a number of string-handling function s, including LCase$ and
UCase$, which translate strings to lowercase and uppercase letters, respectively. To add
uppercase translation, you app ly the U Case$ function to the contents of the Source text box :
Sub Dup_Click ()
Dest.Text - UCase$(Src . Text)
End Sub

After making this change and running the appl ication again, you'll find that the Dup
command button not only copies text from Src to Dest, but also translates that text to ali
uppercase letters.
For more information on UCase$ and LCase$, see the Language Reference , or:

m Search Help for:


lowercase

Performing System Commands


Command buttons can exec ute operating-system commands or run other programs. This
makes it easy for you to create a "shell " app lication that gives users quick access to the
programs and files they need in their daily work.
To run system commands or other executab le programs, use the Shell function :
Shell( commandstring$)

The argument commandstring$ is the name of the program or command to be exec uted.

Microsoft Visual Basic Programmer's Guide


106 Part 3 Appl icati on-Building Tech niques

For exam ple, Figure 10.4 shows an application you might develop for a proj ect man ager
who wants qu ick access to di fferent types of information. By clicking a comm and button,
the manager can qui ckl y view a proj ect plan, schedule, ora list of people workin g on the
proj ect.

111 Project Planner • aa


Project Plan - U pdate monthly
[':'.lan ¡

La test Schedule- R evi sed 10/2/9 1


Schedule

Names. phone numbers . addresses


Contacts

Figure 10.4 A shell appl ication

The appli cati on has th e fo ll owi ng properties.


Control CtlName property Caption property
To p com mand button Plan Plan
Middle co mmand button Sched Schedul e
Bottom com mand button Cont Contacts
To p label Projec t Plan-- Update
monthl y
Middle label Latest Schedul e--Rev ised
10/2/9 ]
Bottom !abe! Names, ph one numbers,
addresses

The Click proced ure for the Plan com mand button starts Mi crosoft W ord fo r Windows and
ope ns the fi le con taining the project plan:
Sub Pl an _ Click ()
x - Shell( " \winword \ win word .exe plan.doc " , 1)
End Sub

The Click procedure fo r th e Sc hed ul e co mm and button starts Mi crosoft Proj ec t fo r Windo ws
and loads the schedul e fi le:
Sub Sched Click ()
y = Shell( " \ winpr oj\winproj.exe sc hedule. wpr " , 1)
End Sub

Microsoft Visua l Basic Programmer's Guide


Chapter 10 Responding to Comm and s 107

To keep track of names and addresses, the manager uses the Cardfile appli cation th at comes
with Microsoft Windows. The Click procedure for the Contacts command button is:
Sub Cont _ Click ()
z = Shell("\windows\cardfile.e xe prjnames . crd", 1)
End Sub

Each of these procedures starts a Windows application in a normal window . You also can
start them in minimized or maximized windows.
Note that the three Shell functions above return values to variables x, y , and z. This return
value is not used in the project manager application, but you may find it useful in other
applications. The value identifies the program started by Shell and indi cates whether the
program started successfully .
For more information on the Shell function , see the Language Ref erence , or:
Search Help for:
111 Shell

Controlling Command Buttons at Run Time


Y ou can change the state of a control at run time by setting properties. In the case of
command buttons, there are several actions you may find useful , as shown in th e followin g
table.
Action Technique Purpose
Di sabling Set Enabled property to Prevents user from choosing
False (O) the co mm and
Enabling Set Enabled property to Enables user to choose the
True (-1) command aga in
Making invisible Set Vi sible property to Disables th e co ntrol and
False (0) removes it fro m the visible
form

When you disable or enable a command button, you're controlling the user' s access to the
comrnand. Generally, you di sable a command because the comrnand is either impossible or
inappropriate at the time-for example, when a comrnand is supposed to del ete a specified
file , but the file is read -only .
The techniques di sc ussed here require setting certain Boolean properties to True or False.
The next section shows how to do this with the assignment statement.

Enabled-a Boolean Property


The Enabled property is an example of a Boolea n property: It takes th e va lue True or Fal se.
Vi sual Basic stores Boolean values as integers. Ali non-zero integers equ ate to True, and O
eq uates to False .

Microsoft Visual Basic Programmer's Guide


108 Part 3 Application- Buil ding Techniq ues

T his means you can set a Boolean property to True- th at is, "turn it on" - by assignin g any
integer other than zero. Far example, any of these statements enable th e DoAction command
button:
DoAction.Enabled - 3
DoActio n .Enab l ed = 1776
DoAct i on.Ena bled - - 1

To turn a Boolean property off, set it to O. For example, the fo llowing statement di sables the
DoAction command button :
DoAction.Enaoled - 0

However, although you can assign any non-zero value to turn a Boolean property on , Visual
Bas ic stores it as - l. The safes t course of acti on is to use - 1 exclu sive ly for True .
You can make your code more readable by placing the fo llowi ng Const (constant)
defi nitions in the Declaratio ns sec tion of the form or modul e:
Const TRUE= -1
Const FALSE= 0

Then use True and False i'rrstead of - 1 and O.


You can define True and False in the global module by using Global Const statements,
whi ch are available in the fil e CONSTANT.TXT. You can either copy the defi nitions you
need from that file or co py the entire file into the global module.
For more information on the Const statemen t, see Chapter 17 , " Adva nced Language
Features"; the Language Reference; or:

Search Help for:


111 Const
Finding Out if a Command Button Is Enabled
You also can use the E nabled property to find out whether a button is enabled or di sabled .
The following exampl e di splays a message in a text box named Reado ut that indicares
whether th e DoAction command button is enabl ed:
If DoAct ion.Enabled Then
Readout.Text "The button is enabled."
Else
Readout.Text "Th e button is disabled."
End If

Ali co ntrol s except frame and label control s have the Enabled property ; you can use similar
code to disable a co ntrol orto find out if it is enabled.

M ic rosoft Visual Basic Programmer's Guide


Chapter 10 Responding to Commands 109

Creating a Menu-Driven Application


Visual Bas ic enables you to build menus in your applications - including hierarchical
menus with up to six levels. A hiera rchical menu includes one or more submenus th at open
off another menu to di splay their own cornmands.
Writing code far menus requires a Click event procedure far each command. Each command
is a contro l, and the Click event is invoked when th e user chooses the command.
This section illustrates how to create and use menus with an application called Try Menus.
The nex t secti on, "Controllin g Menus at Run Time," explains how to make menus more
fl exible by enabling or di sabling menu com mands, adding check marks, and makin g menus
grow or shrink - all at run time, in response to user actions.

How the Try Menus Application Works


The Try M enus appli cati on has a fo rm with two menus: Action and Infa. Figure 10.5 shows
how the form looks, firs t with the Action menu displayed and then with the Info menu .

N umber rea dout: N umbe, rea dout:

lnfo,m ati on bo,c: 1nform ation box:

Figure 10.5 Action and lnfo Menus

When the application is compl ete, its me nus work as fo llows:


• The Squ are and Square Root co mmands on the Action menu perfarm a calcul ati on on th e
number in the top tex t box.
• The Date, T ime, and Program Name commands on the Info menu display infarmation in
the bottom tex t box.

The properti es of the tex t boxes are listed in the fo ll ow ing tabl e.
Control CtlName property Caption property
Top tex t box Readout
Botto m tex t box InfoBo x
Top label Number readout :
Bottom label Jnfo rm ati on box:

Microsoft Visua l Basic Prog rammer's Guide


110 Part 3 Application-Building Techniques

Building the Menu Interface


Menus are special kinds of controls. You create them and specify properties by using the
Menu Design window rather th an the Toolbox or Properties bar. Figure 10.6 shows the
Menu Design window when information has been added for the Action and lnfo menus.

Menu Design Window

CaQtion: \~ 1 1 -º_one

CtlName: \ActionName 1 1 Cancel

lndel!.: C:=J Accelerato, : j[none) li]


O _!;_hecked 181 [nabled 181 Y.isible
1+- 1+ 1-. 1+ f I Next 11 !nsert ll D~lete
Aclion
···· Square
···· Square Root
lnfo
···· Date
···· Time
·· Program Name

Figure 10.6 Menu Design window far the Try Menus application

Each e ntry in the Menu Design window creates one menu control, and each menu control
co rres ponds to a men u item. Menu items include menu names, commands, separator bars,
and subme nu names. The items in the Menu Design window work like thi s:
• If a menu item is not inden ted. its caption appears on the menu bar as a menu name .
Menus whose names appear on the menu bar are top-l eve! menu s, as opposed to
submenu s, whose names appear on other menu s. Top-leve] menus usually are just call ed
menu s.
To qui ckly see which menu names will appear on the menu bar, sean down the left of the
Menu Design window; eac h item that isn't indented is a menu name.
• Each item that follows a menu name, and is indented only once (preceded by four dots),
appears as an item on that menu .
Menu ite ms can include commands, separator bars, and subme nu names. To qui ckl y see
which ite ms will appear on a menu, sean down the items th at follow a menu name; eac h
ite m indented only once is an item on that menu.
• An ite m th at is indented twice (and thu s is preceded by eight dots) is an item on a
submenu . As with items on a top-level menu, items on a submenu can include
commands, separator bars, and other submenu names.
To qui c kl y see which items wi ll appear on a submenu, sean down the ite ms that follow
th e subme nu name ; each item inde nted once more than the name is an item on th at
subm e nu .

Microsoft Visual Basic Programmer's Guide


Chapter 10 Responding to Commands 111

• To create additional levels of submenus, just indent items more to the right.
Visual Basic supports five levels of indentation. Therefore, each of your menus can have
up to four levels of submenus. The fifth level can include commands and separators, but
not submenu names .
• If a menu item has a Caption setting consisting of a hyphen (-), it appears as a menu
separator bar. A separator bar divides items into logical groups on a long menu .
• All menu items except separator bars recognize the Click event. The Click event
procedure for each item (remember that each item is a control) is invoked when the user
chooses it.
Generally you write event procedures only for items that are commands. You can
consider the Click event for a menu or submenu name to be a "drop-down" event: It
inforrns you that the menu or submenu is about to be opened.

To create the Try Menus application, set the following properties in the Menu Design
window.
Caption CtlName lndented
Action ActionName No
Square SquareCom Once
Square Root SquareRtCom Once
Info InfoName No
Date DateCom Once
Time TimeCom Once
Program Name ProgCom Once

Note To start indenting items in the Menu Design window, click the right arrow halfway
down the window. Subsequent items will have the same indentation, but you can use the left
and right arrows to change an item 's position .

Attaching Code to the Action Menu


Each command in the Action menu needs code for its Click event procedure, so that it wi ll
respond when the user chooses it. You don't have to enter code for any of the menu names
in thi s application.
The SquareCom_Click procedure carries out the Square command by reading the contents of
the Readout text box, squaring that number, and displaying the result:
Sub SquareC om_Click ()
Amt = Val(Readout . Te xt)
Amt = Amt * Amt
Readout.Text = Str$(Amt)
End Sub

Microsoft Visual Basic Programmer's Guide


112 Part 3 Application-Building Techniques

The first statement (after the procedure heading) tran slates the text string in Readout into a
numeric value. The last line of code (before End Sub) tran slates the result back into a string
and stores thi s string in Readout.
T he SquareRtCom_Click procedure carries out the Square Root command approximately the
sa me way, but with a different calculation :
Su b Square RtCom_Click ()
Amt = Val(Readout.Text)
Amt = Sqr(Amt)
Readout.Text - Str$(Amt)
End Sub

Attaching Code to the lnfo Meilu


The In fo menu has three commands-Date, Time, and Program Name - whi ch are created
with controls named DateCom, TimeCom, and ProgCom. When the user chooses the Date
cornrnand, the DateCom_Click proced ure di splays the current date in the InfoBox text box :
Sub DateCom_Click ()
InfoBox.Text - Date$
End Sub

The TimeCom_Click procedure shows the current time in InfoBox:


Sub Ti meCom_Clic k ()
InfoBox.Text - Time$
End Sub

The two event procedures use the reserved words Date$ and Time$. These words look li ke
st rin g variables but are act uall y string function s. Visual Basic responds to these fun ction s by
suppl ying the current date or tim e to yo ur app licati on.
For more information on Date$ and Time$, see the Language Reference , or:

Search Help for:


111 now

The ProgCom_Click procedure disp lays the na me of the app lication :


Sub ProgCom_Click ()
InfoBox.Text - "Pr ogram name is Try Menu s. "
End Sub

Mic rosoft Visual Basic Programmer's Guide


Chapter 10 Responding to Commands 113

Controlling Menus at Run Time


Your menus can respond dynamically to run-time conditions. For example, your application
might determine that sorne menu command should not be carried out, so it prevents the user
from selecting it. Or the application might use a check mark to indicate which of severa!
commands was last selected. Your application can also add or delete menu commands.

Enabling and Disabling Menu Commands


An application can disable a menu command or even an entire rnenu in the same way it can
disable a comrnand button. Ali menu names and menu commands have an Enabled property ;
set this property to False (O) to prevent the user from choosing the ítem. When this property
is set to False, the menu is disabled and does not respond to user actions.
These statements disable the Date and Time menu comrnands in the Info rnenu described in
the previous section:
DateCom.Enabled - 0
TimeCom .Ena bled = 0

Disabling a menu name has the effect of disabling the entire rnenu , since the user cannot
access any menu command without first clicking the menu name . This statement disables the
Info menu :
InfoName.Enabled = 0

An Application that Uses a Check Mark


To puta check mark next to a menu command, set its Checked property to True (-1). For
example:
DateCom.Checked = -1

There are two main reasons for placing check marks on menus:
• To tell the user the status of an on/off condition. Choosing the menu command
alternately adds and removes the check mark.
• To indicate which of severa! modes is in effect. This use of check marks is similar to
option buttons, in which one of several options is in effect.

Thi s sec tion illustrates the second case described above with an application that operates in
oc tal, decimal , and hexadecimal mode. The Number System ap plication has three menu
commands: Octal, Decimal, and Hex . A check mark appears on the menu to show which of
the three number sys tems is in effect.

Microsoft Visual Basic Programmer's Guide


114 Part 3 Application-Bui ld ing Techniques

The application shown in Figure 10.7 has a menu anda text box named "Readout."

Hex
197 1

Figure 10.7 A menu command with a check mark

When the user chooses one of the menu commands, the application converts the number in
the text box to the indicated number system. For exarnple, if decimal mode is in effect and
the user chooses the Hex command, the digit string "64" is redisplayed as its hexadecimal
eq uivalent, "40."
To create the menu, enter the following information in the Menu Design window. The check
mark next to the DecimalCom control indicates that the application initially uses decimal
numbers.
Caption Name lndented Checked
System SystemName o No
Octal OctalCom Once No
Decimal DecimalCom Once Yes
Hex HexCom Once No

Note This application uses Visual Basic defaults fo r the se iterns in the Menu Design
window: Index , Accelerator, Enabled, and Visible.

Attaching Code to Control Check Marks


The code for the application has four procedures.
The first three procedures respond to ali the Systern menu comrnand s. Each menu command
responds by reading the number using the existing number system , moving the check mark,
and displaying the number in the new sys tem (using the Oct$, Str$, or Hex$ function):
Sub· OctalCom_Cl ick (J
Amt - ReadV alue(Readout.Text) ' Read in number.
OctalCom.Checked = - 1 ' Reset check mark.
DecimalCom.Checked = 0
HexCom.Ch ecked - 0
Readout.Text = Oct$(Amtl ' Display number .
End Sub

Microsoft Visual Basic Programmer's Guide


Chapter 10 Responding to Commands 115

Sub DecimalCom_Click ()
Amt - ReadValue(Readout . Text) ' Read in number .
OctalCom.Checked = 0 ' Reset check mark .
DecimalCom.Checked - -1
HexCom.Checked - 0
Readout.Text - Format$(Amt) ' Display number.
End Sub

Sub HexCom_Click ()
Amt - ReadValue(Readout.Text) ' Read in number .
OctalCom.Checked = 0 ' Reset check mark
DecimalCom.Checked - 0
HexCom.Checked = - 1
Readout.Text = Hex$(Amt) ' Display number.
End Sub

Each of the procedures reads the contents of Readout by calling a general procedure,
ReadValue. This same code could be placed in every procedure, but by placing it in a
Function procedure you save yourself from typing the same code several times:
Function ReadValue (ByVal Digit s$)
If OctalCom.Checked Then
ReadValue - Val("&O" + LTrim$ (Digits$) + "&")
Elself DecimalCom . Checked Then
ReadValue Val(Digits$ + "&" )
Else
ReadValue = Val("&H" + LTrim$ (D igits$) + "&")
End I f
End Function

The ReadValue procedure tests to see which menu command is checked, because the
placement of the check mark indicates which number system to use. The procedure then uses
the Val function to get the numeric value. Note that adding a "&O" prefix causes Val toread
the digits asan octal string, anda "&H" prefix causes Val toread the digits as a hex strin g.
The LTrim$ function removes leading spaces from the number in the text box.
Appending an ampersand (&) enables the application to support conversion of larger
numbers. The ampersand suffix causes th e Val function to interpret the digit string as a long
integer.

Microsoft Visual Basic Programmer's Guide


116 Part 3 App lication -Building Techn iq ues

Adding and Deleting Menu Commands


Sorne menu s grow or shrink at run time. A good example is the Window m enu in the
W indows Program Man ager, show n in Figure 10.8. The bottom section of thi s menu has one
ítem for each of the program groups yo u' ve created. If you create another program group ,
the menu grows. If you delete a program group , the menu gets s maller.

f ile Qptions .!::!. 1

lil e
Arrange lcon s
✓ l Windows Application s
Z. Acce ss orie s
l Main
~ Mi cro s oft Vi sual Bas ic

Figure 10.8 The Window menu of th e Program Man ager

Yo ur Vis ual Bas ic applications can have rnenu s th at change size durin g run time. These
rnenu s have commands that are part of a control array.

What Is a Control Array?


A con1rol array is a set of simil ar co ntrols that share the sam e name and th e sa me event
procedures. To create a new co ntrol at run time, it rnu st be a member of a control array.
For cxample, suppose yo u tried to create a co ntrol at run time, and it was no t part o f a
control array. W hat code wou ld Visua l Bas ic assoc iate w ith it? Where wo uld th e eve nt
procecJures come from ? With a control array, each new e lement inherits the corn mo n event
proccclures of the array.
The elements of a co ntrol arra y are physicall y separate controls, each wi th th eir ow n
property se ttin gs. However, they share the same narne code, as shown in Fig u·re 10.9.

Code Comm on event procedures


(shared) for
Co mbos( )

1 1
Data property property property prop erty
(prívate) settings settings se ttings settings
lndex = O lndex = 1 lndex =2 lndex =3

Figure 10.9 A Contro l Array

Microsoft Visual Basic Programmer's Guide


Chapter 10 Responding to Commands 117

Noti ce how each control is referred to with the syntax controlname (index ). You specify the
index of a control when you create it. In fact, specifying any index at design time makes the
control part of an array .
When the control Combos(2) recognizes the Click event, Visual Basic invokes the event
procedure Combos_Click, and passes the number 2 asan additional argument.

An Application that Adds and Deletes Menu Commands


The Application Manager application shows how you rnight use a control array to add and
delete menu commands at run time. The application has a menu with two commands anda
separator bar, as shown in Figure 10.1 O.

. . . .. . ,, .

Figure 10.10 Application Manager

When the user c hooses th e Add Application comrnand, a new item is added to the bottom of
the menu . When the user chooses Delete Application, a message asks for an index number of
an item to remove from the bottom part of the menu.
The menu co ntrols are created in the Menu Design window, with these property settings.
Caption CtlName lndented lndex
Applications App No
Add Application AddApp Once
Delete Application De!App Once
AppNafl)e Once o
The last co ntrol on the list, AppName, has its caption set to a hyphen (-), which causes
Visual Basic to display a separator bar.
Because AppName is assigned a value for the Index property, it automatically becomes an
eleme nt of a co ntrol array-even though no other elements ha ve been created yet. At run
time, the fo llowing stateme nt creates ano ther ele men t of the array :
Load AppName(l)

Microsoft Visual Basic Programmer's Guide


118 Part 3 Application-Building Technique s

At run time thi s statement adds another item to the menu , just below the separator bar. The
next statement deletes this same element:
Unload AppName(l)

You can use the Unload statement only with controls that were created with the Load
statement; you cannot remove controls created at design time. Therefore, you cannot delete
the separator bar, which is the first element of AppName.
The procedures in this application use a variable called LMen u to track how many items are
on the menu . The variable should be declared in the declarations section of the form:
Dim LMenu As Integer

Once so rne commands have been added to the bottom of the menu, it's a simple matter to
execute the m. AppName_Click is the common eve nt procedure for ali of these commands.
The procedure works by simply passing the control ' s caption to the Shell function . Note that
the control chosen is identified as AppName(lndex):
Sub AppName_Click (Indexas Integer)
x = Shell(AppName(Inde x).Caption. 1)
End Sub

When the user chooses the Add Application comrnand, Visual Basic calls the
AddApp_Click procedure. Thi s procedure asks the user to suppl y the name of an
application:
Sub AddApp_Clic k ()
Msg$ = "En ter path:" ' Mes sage to di sp lay to user.
FileSpec$ = InputBox$(Msg$) ' Assign user input to FileSpec$.
LMenu = LMenu + 1 ' Increase menu length by one.
Load AppName(LMenu) ' Load new menu command.
AppName(LMenu).Caption FileSpec$ · Set caption far menu command.
End Sub

The second line of code uses the Visual Basic lnputBox$ function to display a box that
prompts the user for a filename (which can include a path). This filename becomes the
caption of the new menu command. The fifth line of code uses the Load statement to
actually add the new menu comrnand.
For more information on lnputBox$, see Chapter 11 , "Genin g Information from the User";
the Language Refe rence; or:

Search Help for:


111 input

Microsoft Visual Basic Programmer's Guide


Chapter 10 Responding to Commands 119

When the user chooses Delete Application from the Applications menu, Visual Basic
invokes the DelApp_Click procedure. When deleting an application, the user specifies the
number of the application (the application just below the separator bar is numbered 1). The
De!App_Click procedure has to do severa! things:
1. Get the number of the menu item to delete.
2. Yerify that the number is in range.
3. If Nis the number of the item to delete, copy the caption of item N+ 1. This makes it
appear that item N has been replaced by item N+ 1. Repeat the process for all items up to
the end of the menu.
4. Delete the last item on the menu .
5. Subtract 1 from LMen u.

The following table shows how: _this process rnight work, given four menu items, if the user
requests that ítem 2 be deleted.
lndex of item Before deletion After deletion Action
l Excel Excel
2* Winword Mines Caption copied from
ítem #3
3 Mines Cardfile Caption copied from
ítem #4
4 Cardfile Removed

The asterisk (*) above identifies the item that the user wished to delete. Note that only the
caption of this ítem changes. However, this is the same as replacing the menu item, because
the functionality of the item depends entirely on its caption.
The code for the DelApp_Click procedure is:
Sub DelApp_Click ()
Dim N As Integer. I As Integer
Msg$ - "Enter number to delete:" · Mes s age to display to user .
N - Val(InputBox$(Msg$)) ' Assign user input to N.
If N > LMenu Or N < 1 Then ' Exit if out of range .
MsgBox "Out of range."
Exit Sub
End If
For I - N to LMenu - 1 ' Rea ss ign capt ion s.
AppName(I).Caption = AppName(I + l) . Caption
Ne xt I
Unload AppName(LMenu) ' Remove last item.
LMenu = LMenu - 1
End Sub

Microsoft Visual Basic Programmer's Guide


120 Part 3 Application -Building Technjques

The De!App_Click procedure introduces use of the Exit statement, which exits immediatel y
from the procedure. The use of thi s statement prevents the deletion from taking place if the
number is out of range. For more information on Exit, see the Language Reference, or:

m Se_arch Help for:


ex1t

Shortcut and Access Keys


You can provide keyboard comrnands in your application s in two ways:
• Shortcut keys. These execute a menu command immediately when pressed, and include
function keys and control-key combinations, such as CTRL+A.
• Access keys. These enable the user to choose a control or open a menu by typing a
designated letter while holding down the AL T key . Once a menu is open, the u ser can
choose a comrnand by pressing just the letter (the access key) assigned to it.

To assign a function -key or control-key shortcut to a menu command, select from the list in
the Accelerator drop-down list box in the Menu Design window. Choose "(non~)" from the
top of the list to cancelan assignment.
To use a letter asan access key, placean ampersand (&) in front of the letter in the Caption
property setting. Most often, the access key is the first letter of the caption . You can assign
access keys to any control that has a Caption property, and to any menu name or comrnand.
For exarnple, the following Caption propert y settings respond to the letters O, S, and A:
&Open
Clo&se
Save &As

The arnpersand itself is not displayed on the control or menu ; instead, an underscore appears
beneath the designated letter.

Note Avoid giving multiple objects the same access key. Ideally, each control should have
a unique access key so that the key doesn' t have to be pressed repeatedly to get to the
desired object.

Access Keys for Text Boxes and Pictures Boxes


When a control has an access key but canno t receive the focus (because, for example , it is a
label), the focus moves to the next control in th e tab order. (Tab arder is the order in which
the user moves from one control to another by pressing the TAB key.) This feature enables
you to ass ign an access key to a text box , even though it doesn't have a Caption property.

Microsoft Visual Basic Programmer's Guide


Chapter 10 Responding to Commands 121

To assign an access key to a text box:


1 Place the label just before the text box in the tab order.
Toe easiest way to do thi s is to create the label first, then create the text box. (See the
next section , "Controlling the Tab Order.")
2 Use an ampersand in the !abe!' s Caption property to indicate the desired access key.
The access key assigned to the label then becomes the access key for the text box . The
user can use the access key to move the insertion point to the text box.

Note You can use the same technique to assign an access key to a picture box.

Controlling the Tab Order


Visual Basic assigns tab order according to the order you create the controls on a form. For
example, assume you create two text boxes (Textl and Text2) anda command button
(Commandl)-in that order. At run time, Textl has the focus on startup. Pressing TAB
moves the focus between controls in this order:
Textl
Text2
Commandl

When Command] is the act ive control , pressing TAB moves the focus back to Textl.

What' s in the Tab Order?


All controls except timers and menu controls are a part of the tab order. Sorne of these
controls-i ncluding frames , labels, and any control disabled or made invisible-cannot
receive the focus. As the user presses the TAB key, these control s are skipped.
Many types of contro ls have a TabStop property . Thi s property is set to True by default. If it
is set to False, the control is ski pped when the user cycles through.controls by pressing TAB .
The placement of frames and labels in the tab order is significant because this order
determines the affect of access keys associated with the control. Pressi ng the access key
moves the foc us to the next control in the tab order that can receive the focus . (See the
previou s section, "Shortcut and Access Keys," for more information .)

Microsoft Visual Basic Programmer's Guide


122 Part 3 Application-Building Techniques

Changing the Tab Order


To specify a different tab arder, change the value of the Tablndex property for one or more
controls. The Tablndex property specifies the position of a co ntrol in the tab arder,
begi nning with the number O. In the example given earlier, the controls Textl, Text2, and
Command l have Tablndex settings of O, 1, and 2, respectively.
When you change the Tablndex property for a co ntrol , other controls are renumbered as
appropriate. For example, suppose you set the Tablndex property for Commandl to O. You
can do this at design time by usi ng the Properties bar. You can also make thi s change at run
tim e with thi s statement:
Commandl.Tabindex = 0

Settin g Tablndex to O places Command 1 first in the tab arder. The Tablndex for the other
controls are au tomatically adj usted up ward, as li sted in the following table.
Tablndex before Command1 Tablndex after Command1
Control name becomes first in Tab order becomes first in Tab order
Textl o 1
Text2 l 2
Commandl 2 o
Whenever you change a Tablndex setting, Visual Basic adju sts the Tablndex property for
each control as necessary , so that the first control in the arder has a Tablndex settin g of O,
and the other cont,·ol s are numbered sequentiall y.
The highest Tablndex setting is always one less than the number of controls in th e tab arder.
You ca n set the Tabln dex property to a number large r than the numbe r of controls; this has
the effect of moving the control to the e nd of the tab arder. For exa mple, if there are ten
co ntrols in the tab arder, th e Tabindex settin gs run from O to 9. If you assign the value 15 to
a control's Tablndex property, Visual Basic converts this value to 9 and moves th e control to
the back of th e tab arder.
If you assig n a Tablndex value less than O, Visual Basic generates an error.

Micro soft Visual Basic Programmer 's Guide


_.•.••r• • ••~•,"-,'f.,,.~~;J!-,,• •4, ;... , P \ •~ ~ \ _;; •!-.., ,• •• ,v,~ ., • --¡•?, ..,,••,,,,:

.. · e h a p t e r 1 1 ·

Getting lnformation from the User

Microsoft Windows and OS/2 Presentation Manager provide a variety of input mechanisms,
which in Visual Basic are implemented as controls. By using each control for its intended
purpose, you add variety, make your applications easier to use, and maintain consistency
with other applications .
Text boxes are good input devices (because most types of information can be represented as
text) , but require the user to type. Option buttons, check boxes, list boxes, and combo boxes
enable the user to choose from a set of altematives. Scroll bars provide a graphical way to
indicate a number: The user changes a value by adjusting an indicator on a scale.
An altemative to data entry is the use of the lnputBox$ function, which prompts the user for
input by displaying a dialog box.
The main sections in this chapter are:
• Advanced Use of Text Boxes
• Providing Choices with Option Buttons
• Using Check Boxes
• Providing Choices with List and Combo Boxes
• Getting Input with Scroll Bars
Prompting for Input with InputBox$
124 Part 3 Application-Building Techniques

Advanced Use of Text Boxes


Text boxes are versatile controls that can be used in a variety of ways. T he next four sec tions
di sc uss these uses of text boxes :
• Multiline Text Boxes and Word Wrap
• Validating Data in a Text Box
• Changing and Restricting Keystrokes
• Replacing the Decimal Separator

Multiline Text Boxes and Word Wrap


The look and behavior of a text box is strongly inf!uenced by two properties, MultiLine and
Scroll Bars, which are set at design time only. The ScrollBars property should not be
confused with scroll bar controls, which are not attached to text boxes and have their own set
of properties.
Setting MultiLine to True (-1) enables a text box to accept or di splay multiple lines of text at
run time. You cannot use the Properties bar to enter multiple lines of text at design time,
even if Mu ltiLine is set to True. However, you can use a Form_Load procedure to put text
into a te xt box on startup.
Within a procedure, you create a line break by in sert ing a newline character - a carriage
re tum fo llowed by a linefeed (ASCII characters 13 and 10). For exampl e, the following
event proced ure puts two lines of text into a multiline text box (Textl) whe n the form is
loaded:
Sub Form Load ()
NL$ = Chr$ ( 13) + Chr$(10) 'Define newline character.
Textl . Tex t = "H ere are t wo lines" + NL$ + "in a text box."
End Sub

When ent ering text, th e user can insert a line break by pressing ENTER- unless a command
button with the Default property set to True is present on the form. If thi s is the case,
press ing ENTER chooses the button, and CTRL+E TER inserts a line break in the text box.
A multiline tex t box automatically manages word wrap as long as there is no horizontal
sc ro ll bar. The ScrollBars prope rty is set to None (O) by default. Automatic word wrap saves
th e use r the trouble of inserting line breaks at the end of lines. When a line of text is longer
th an what can be di splayed on a line, the tex t box wraps the text to the next line.

Microsoft Visual Basic Programmer's Guide


Chapter 11 Getting I nformation from the User 125

Validating Data in a Text Box


You can use a LostFocus event procedure to validate data as soon as the user commits the
change. If the new data (specified by the Text property) is not within the valid range for your
application, your code can simply restore the previous value. Your application can beep or
display a warning message explaining why the data is not accepted .
For example, the text box in Figure 11 . 1 accepts numbers from 1 to 10. If the data entered in
the text box is not valid, the applicati on is programmed to beep.

!ZI Validation Example aD

Entera number from 1 to 10: 1~


1- - ~

Enter your name:

Figure 11.1 Validation Example

The controls have the following property settin gs .


Control CtlName property Caption property Text property
Top text box Readout 1
Top label Enter a number
from 1 to 10:
Bottom text box Your name (blank)
Bottom label Enter your name:

The Declarati ons section of thi s form de fi nes a form -level vari abl e that holds the most recent
acceptable value entered in the tex t box :
-~
Dim MyN um As In te ge r

Note Visual Basic recogni zes a seri es of events every ti me a form is opened. The Load
event is always the first event to occur, and the Form_Load event is the place to initi ali ze
any form -level variables. Any vari ables you don' t initi ali ze start out with the value O or, in
the case of strings, an empty stri ng.

Microso ft Visual Basic Prog ramm er's Guide


126 Part 3 Application-Building Techniques

The LostFocus event procedure for the Readout text box performs the data validation as
shown here :
Sub Readout_ LostFocus ()
Amt = Val(Readou t.Text)
If Amt < 1 Or Amt > 10 Then
Beep
Readout.Text = Str$(MyNum)
Else
MyNum = Amt
End I f
End Sub

When this procedure is invoked, the user has just changed the contents of the Readout text
box. The first step of this procedure is to convert the stri ng of digits in Readout to a numeri c
value:
Amt = Val(Read out . Text )

The procedure then tests Amt to see if it is within the acceptable range. If not, the procedure
performs these statements:
Beep
Readout.Text = Str$ ( MyNum)

The Beep statement produces a warning beep to indicate an error. The assignment statement
on th e next line resets th e contents of Readout to the previous acceptable va lue, stored in
MyNum .
If Amt is within range. then the procedure sets MyNum to the new value:
MyNum = Amt

To summar ize, the proced ure tests to see if the number entered is valid. If so, it assigns the
value to the form-level variabl e, MyNum . lf not , the display is restored by reading back the
va lue of MyNum.

Changing and Restricting Keystrokes


Responding to the KeyPress event enables you to restrict characters or transform them as
they are typed. The KeyPress event is the easiest of the three keyboard events to write code
for. Unlike the KeyDown and KeyUp events, the KeyPress event is generated only when a
standard ASCII character is input. Thi s does not include most of the spec ial keys, such as
function keys, the arrow keys . or th e DEL key .

Microsoft Visual Basic Programme r 's Guide


Chapter 11 Getting lnformation from the User 127

Note The ASCII characters are a subset of the ANSI character set in Visual Basic. ASCII
characters include all the printable characters, the CTRL key combined with an A-Z
character, a few other standard characters such as ENTER (ASCII 13), and the BACKSPACE
key (ASCII 8). You can transform or cancel any of these keystrokes with the KeyPress
event. To have your code respond to a key that <loes not produce an ASCII character, use the
KeyUp or KeyDown event.

The KeyPress event uses one argument, KeyAscii. This argument represents the numeric
(ASCII) equivalent of a printable character. You must translate thi s argument if you want to
evaluate itas a character.
Here is a common sequence for doing things within a KeyPress event procedure:
1. Translate Key As e i i into a charac ter by using the Chr$ function, which returns a
one-character string.
2. Perform whatever operations or tests are appropriate with this string. Remember that the
relational operators (=, >, <, <=, and >=) ali work on strings and use alphabetical arder to
define "greater than" and "less than."
3. To change the character the control receives, translate the character back to numeric
format with the Ase function, then assign this result to Key As e i i .
To cancel the keystroke so that the control receives no character, assign O to Key As e i i.

Man y kind s of objects recognize the KeyPress event, but only text boxes and combo b0xes
di splay charac ters as typed. Therefore the third step above is relevant only to text boxes and
combo boxes.
The fo ll owing example translates characters to uppercase as the user types them; the
KeyPress procedure receives the key stroke, changes it to uppercase, and uses the Ase
function to change the character back to a number. This code assumes that Readout is a text
box:
Sub Readout _KeyPress (KeyAscii As Integer)
C$ = Chr$(KeyAscii) ' Convert to character.
C$ = UCase$(C$) ' Change character to uppercase .
KeyAscii = Asc(C$) ' Convert back to numeric .
End Sub

The first indented line changes the data format to string, and the third changes it back to
numeric again. The middle line does the real work of the procedure. It uses the U Case$
function to change the character to uppercase . (UCase$ has no effect on the character unless
it is a lowercase letter.)

Microsoft Visual Basic Programmer's Guide


128 Part 3 Application -Building Techniques

The nex t exa mple demonstrates how to restrict keystrokes; if the character typed is not
within range , the procedure cancels it. The text box for thi s example is named EnterNums,
and the procedure prevents the text box from receiving any characters other than di gits:
Sub Enter Num s_KeyPress (KeyAscii As Inte ger)
C$ = Chr$ ( Key Asci i) ' Con ve rt to character.
If C$ < "0" Or C$ > "9" Then ' If out of range,
Key Ascii = 0 kill the character.
Beep ' Sou nd erro r s ignal .
End I f
End Sub

You can optimize exec ution speed sli ghtly by not translating Key As e i i to a string. Instead,
compare it directly to the numeric (Ase) values of various characters. For example, the
examp le above could be rewritten as:
Sub EnterNum s_KeyPress (KeyAscii As Integer)
If KeyAscii < Asc("0") Or KeyAsci i > Asc("9") Then
KeyAscii = 0 'Kill the character.
Beep ' Sound error signal.
End I f
End Sub

Replacing the Decimal Separator


In many co untri es, the comma (,) is used to indicate decim al place, rather than the point (.).
This difference ca uses a problem with th e Val function , which assumes the use of the
dec ima l po int. If you support use rs who use the comma instead of th e point, add th e
fo ll owing general procedure to your application:
Fun ction MyVal(ByVal A As String) As Double
X= In Str(A. "," )
If X> 0 Then Mid$(A, X. 1) =
My Val = Val (A)
End Funct i on

Then, cal! the MyVal Function procedure when you need to tran slate from string to number.
The procedure works by rep lacing the first comma with a point (.), and then passing the
res ulting string to the Val function. The intrinsic InStr function finds the position of the
comma, and th e Mid$ statem ent puts a point at that position . For more information on
strings, see the Language Reference, or:

m Search Help for:


stnng

Microsoft Visual Basic Programmer's Guide


Chapter 11 Getting lnformation from the User 129

Providing Choices with Option Buttons


When the user has to choose from a limited set of alternatives, you can use option buttons to
display those choices and make selection easier. Instead of typing, the user simply clicks a
button.
For example, when usi ng the form in Figure 11.2, the user selects one of three option buttons
to select a charge card .

IZI Option Button Example DD

S e lec t pay me nt method:

®f\.ii~~J O MasterCard O Amex

Figure 11 .2 Using option buttons to give the user a choice

An option button alw ays works as part of a group. Selecting an option button immediately
causes ali other buttons in the group to be cleared. Defining an option button group tell s
Visual Basic, " Here is a set of choices, from which the user picks one and only one."
Ali of the option buttons placed directly on a form (not in a frame or picture box) constitute
one group .

Note If you want to create more th an one group of option buttons , you must place sorne of
them inside frame s or picture boxes . Ali the option buttons inside any g iven frame constitute
a separate group. as do ali the option buttons inside a picture box. When crea tin g a separate
group thi s way, always draw the frame or picture box first , then draw the option buttons .

The Value property of an option button shows whether or not it is selected . This property is
True (-1) if the button is selec ted and False (0) if not. To selec t a button from within a
procedure. set its va lue to True:
Ame xButton.Value = - 1

The Click event occ urs when the user selects an option button at run time. Oncean option
button is selected, you can assume that it remains selec ted and that its Value property is set
to True (- 1) until the user selects a different option button.
The user se lec ts an option button either by c licking it or by tabbing to the button and
pressing the SPACEBAR. You also can cause a ~ li ck event by choos in g the button from within
code, as in thc previous code fragment.

Microsoft Visual Basic Programm er's Guide


130 Part 3 App lication- Building Techniques

Example The fo rm shown in Figure l l.3 uses option buttons to determine which of three number
sys tems (octal , decimal , or hexadecimal) to use. When the user selects a button , the number
d isplayed in the Readout text box is converted to the new number system. Thi s application is
a variation of the one at the end of the section on menus in Chapter l O, " Responding to
Commands ."

1:1 Number System Da

@ Use octal
O Use decimal
O Use hexadecimal

Figure 11.3 Choosing a number system with option buttons

The properties are set as shown in the following table.


Control CtlName property Caption property
Text box Readout
First optio n button OctButton Use octal
Second option button DecButton Use decimal
Third option button HexButton Use hexadecimal

The code for this application is shorter than that for the rnenu-d1iven version for two
reasons: You don ' t have to write any code to move a check mark around, as you do with
menus, and the code in this version uses the Change event.
When you are designing an application , it 's often helpful to write down how the application
should respond to each event. Then it becornes clear how to write the eve nt procedures. This
application responds to events as follow s:
• Change event for the text box : read in the value (usin g the appropriate number sys tem)
and store it in a form- level numeric variable , CurrentNum.
• C li ck eve nt for the OctButton: output Current Num in octal.
• Click event for the DecButton : output CurrentNum in decimal.
• Click event for the HexButton : output CurrentNum in hexadecim al.

What 's key to this approach is the use of a form- level variable, Curren t Num . This variab le
represe nts the value of Readout in num eric form. The Change event keeps thi s value current,
so ali the Click event procedures have to do is output the number in the proper number
sys tem. Curre ntNummu st be declared in the Declarations section of the forrn code:
Dim Curre ntNum As Single

Microsoft Visual Ba sic Programmer's Guide


Chapter 11 Getting lnformation from the User 131

By default, the variable is initialized to O. That's an acceptable default, so there 's no need for
initiali zat ion code.
The Chan ge eve nt procedure checks to see which number sys tem (octal , decimal, or
hexadecimal) is in effect, and then it reads in the number. The number syste m is easi ly
determined from the state of the option buttons. This procedure is similar to the ReadV alue
procedure in Chapter I O, but it looks at the optionbutton.Va]ue condition rather than
menucommand. Checked:
Sub Readout_Cha nge ()
If OctButto n.Value Then
CurrentNum = Val ( "&O " + LTri m$(Readout .Text) + "&" )
Elself DecButton.Value The n
Current Num Val (LT ri m$(Readout.Te xt) + "&")
Else
CurrentNum Val("&H" + LTrim$(Re adout. Text) + "&" )
End I f
End Sub

The Val function is used to tran slate the string to a number, and can recogni ze octal,
decim al, and hexadec imal strin gs. The LTrim$ function strips the tex t of leading bl anks.
The "&O" prefix causes a di git string to be interpreted as octal; the "&D " prefix causes it to
be interpreted as dec imal; and the "&H" prefix causes it to be interpreted as hexadecim al.
The "&" suffi x spec ifies that the number is a long integer; thi s supports use of large r va lues.
The Cli ck event procedures for the option buttons are short. Ali they have to do is use th e
Oct$ , Str$. or Hex$ fun ction to display Cu rrentNum in the appropriate number sys tem:
Sub OctButton Click ()
Readout.Text = Oct$(CurrentNum)
End Sub

Sub DecButton Click ()


Read out.Text = Format$(Cur rentNum)
End Sub

Sub HexButto n Click ()


Read ou t . Text = Hex $(Curr entNum)
End Sub

For more information on opti on button events, see the Language Reference, or:

m Search Help for:


option button

Microsoft Visual Basic Programmer's Guide


132 Part 3 Application-Bu ilding Techniques

Using Check Boxes


A check box control indicates whether a particular condition is on or off, as shown in Figure
11.4. Unlike option buttons, check boxes don't work in groups.

11 Check Box Example aa

Figure 11.4 Che ck Box Examp le

You can have any number of check boxes, but they ali work independently of each othe r.
The user ca n have any number of check boxes selected at the same time.
Cli cking a check box at run time alternately selects and clears it; in either case, each click
action generates the Click eve nt for the box.
The Value property of a check box can be set to one of the following three values .
Setting of Value property Description
O Cleared . The check box is empty .
Selected . An X appears.
2 Grayed .

The fo ll owi ng exa mpl e uses a check box to determine whether or not to tran slate c haracter-,
to uppercase as they are typed. This example builds on o ne of the exa mples in the sec tion
·'C han g in g and Res tricting Keys trokes" earli e r in thi s chapte r.
The application has a check box and a text box , as show n in Figure 11 .5.

11 Character Converter aa

O Conve rt to uppe rcase

Figure 11.5 Wh en th is check box is selected, letters are entered as uppercase.

Microsoft Visual Basic Pro grammer's Guide


Chapter 11 Getting lnformation from the User 133

The following names are assigned to the control s.


Control Setting of CtlName property
Text box Letters
Check box ConvToUpper

The appli cati on includes a KeyPress event procedure for the text box. The procedure tes ts to
see if the check box is selected. If so, it translates the keystroke to uppercase. Otherwi se, the
procedure makes no changes.
Sub Letters _KeyPress (KeyAscii As Intege r)
If ConvToUpper.Value = 1 Then
C$ = Chr $ ( KeyAsci i)
C$ = UCase$(C$)
KeyAscii = Asc(C$)
End I f
End Sub

When the user selects the check box, ali subsequent letters typed in the text box are
converted to uppercase. However, previously typed letters are unaffected. To make the
check box convert the case of all letters in the text box, you can program the Click event for
the check box.
When a Click event occurs, you cannot ass ume that the check box is selected as a result
(because the user also clicks a check box to clear it) . Therefore, the event proced ure has to
test for whether th e check box is selected:
Sub ConvToUpper_Click ()
If ConvToUpper.Value = 1 Then
Letter s.Text = UCa se $(Letters.Text)
End If
End Sub

For more inforrnation on check box eve nts, see the Language Reference , or:

m Search Help for:


check

Microsoft Visual Basic Programmer's Guide


134 Part 3 Application-Building Techniques

Providing Choices with List and Combo Boxes


A list box control gives the user a set of alternatives from which to choose. lf the number of
items exceeds what can be di splayed in the box , the user can scroll up and down through the
li s t.
A list box with five entries is shown in Figure 11.6.

mi List Box Example aa


New Orleans
New York
San Francisco
Seattle

Figure 11.6 A list box

A combo box control combines the fea tures of a text box anda list box. You can use thi s
control to enable the user to make a selection by typing text into the combo box or by
selecting an item from its list.
With the default setting (Style property set to 0), a combo box is a drop-down combo box.
The user can either enter text direc tl y (as in a text box) , or click the detached arrow at the
right of the combo box to open a li st of choices. Selecting one of the choices puts it into th e
text portian at the top of the co mbo box. The user al so can open the list by pressing
A L T + DO W when the control has th e foc us.

The two illustrations at the le ft o f Fig ure I J.7 show a drop-down combo box in its normal
state, and with its li st dropped do,, n.

= 1Porsche 111]
Combo Box Example

1 ~ 11± 1Porsche li}


ªª
Eds el
Feuari

.
Mercedes

Rolls Royce

Combo box Combo box Orop-down


w1th i,st lis t box
dis p la yed
Figure 11.7 A combo box with lis t close d and with list opened, anda drop-down list box

Setting th e Style property of a co mbo box to I specifies a simple combo box , in which th e
list is di splayed at ali times. The use r can still enter text directl y or selec t from the li st.

Microsoft Visu al Basic Programmer's Guide


Chapter 11 Getting lnformation from the User 135

When you want to enable the user to choose onl y from a list, but you want to conserve
screen space, you can use a drop-down list box . A drop-down li st box looks like a tex t box
wi th an attached arrow, as show n at the right of Figure 11 .7. The currentl y-selected ite m is
di splayed in the tex t porti a n, and the user can change the selection by clicking the arro w and
choosing from a list that drops down.
To create a drop-dow n li st box, you draw a combo box and set its Style property to 2.
No te th at a co mbo box with its Style property set to O or 1 enables the user to enter choices
that are not on the li st. In contrast, a drop-down list box (a combo box with its Style pro perty
set to 2), does not permit the user choices beyond those on the li st.
Generall y, a combo box is appropriate when there is a list of suggested choices, and a list
box is appropriate when you want to limit input to what is on the list.
To pl ace ite ms in the li st or remove the m, use the Addltem and Removeltem meth ods
descri bed in the nex t sec ti on.
To access items in a list, yo u use the Text, List, Listlndex, and ListCount properties . Tex t is
usuall y the easiest to work with. Thi s property specifies the selected ítem in string fo rm at.
The List property provides access to all the items in the list, as explained in the secti on,
"Getting at the Contents of a List."
The important events for li st boxes are Click and DblClick; for combo boxes, Click and
Change.

Note Everythin g said in the nex t two sec ti ons, "Placi ng Items in a Li st" and "Gettin g at the
Contents of a List," applies to bo th li st boxes and co mbo boxes, except where oth erwise
noted.

Placing ltems in a List


To place ini tial entri es in a li st box or co mbo box, use the Addltem method, whi ch has thi s
sy ntax:
box.Addltem item [, index]

The item is a string ex pression, and box is a list or combo box. To place a number in the lis t,
first convert it to a string. (If the number is a literal con stant, enclose it in quotation marks; if
it is a variable, convert it with Str$ or Format$) . The brackets indicate that index is an
opti onal argument. If included, index specifies where the new item is to be inserted in the
li st. An index of O represe nts the first position. If index is omitted, the íte m is inserted at the
end .

Note If the Sorted property is set to True (- 1), then Visual Basic always keeps th e items
so rted alphabeticall y, regardl ess of the order you place them there.

Microsoft Visual Basic Progra mmer's Guide


136 Part 3 Application-Building Techniques

The follow ing example places "Chin a," " India," "USSR," and "USA" into the li st box
named Populations - and in that order:
Sub Form_ Load C)
Populations.Addltem " Ch ina "
Populations.Addltem "Indi a"
Populations.Addltem "U SSR"
Populations.Addl tem "USA"
End Sub

Whenever the fo rm is loaded at run time, the li st appears as shown in Figure 11 .8.

= ~ml ªª
'"India.
USS R
USA

Figure 11.8 The Populations List Box

But the next line of code inserts "The UN" into the first position, adjusting th e position of
th e other items downward:
Populations.Add ltem " The UN", 0

You can use the Addltem method at any time . Addltem gives yo u the abili ty to add it ems
to th e li st dynamically (i n response to user ac ti o ns). Yo u can also use the Removeltem
method to delete part of the list. The argumen t index specifies w hi ch item to remo ve:
box. Removeltem index

Getting at the Contents of a List


To acces s the contents of combo boxes and list boxes at run time, use the propertie s be low .
Property Description
T exl The currentl y se lected item , stored as a strin g.
Li st A stri ng array co ntain ing all item s in the li st.
Li stlncl ex The index of the selected ite m, where O is the ind ex of th e
top item . Text is eq ui va len t to List (Listlndex).
Li stCount The number of items in the li st.

Usua lly. th e eas ies t way to get the val ue of the currentl y selected ítem is to use th e Text
property. This property has a string type. (If it contains a strin g of digits, use th e Va l
function to obtain the numbe r. ) With li st boxes, the Text property always co rresponds to
so rn e it e m in th e li st. With combo boxes , th e Tex t property conta ins whatev er is e nt ercd in
th e tex t-box portion of the co ntro l, so it can co ntain a string th at is not in th e li st.

Microsoft Visua l Basic Pro gra mmer's Guide


Chapter 11 Getti ng lnfo rmation from the User 137

Fo r example, the fo llowing code di spl ays information on th e United States if the " USA"
item from the last exampl e is selected:
If Po pulations.Text - "U SA" Then
PopDi sp lay . Te xt = "U SA ha s 250 milli on peopl e. "
End I f

lf yo u' re mainly interested in the relative p osition of the selected item, use the Li stlndex
property. The setting of thi s property is O if the top item is selec ted, 1 if the nex t item down
is selected, and so on. Thus, the code above can be rewritten to test fo r the value "USA,"
whi ch is in the fifth position:
If Populations . List ind ex - 4 Th en
PopDispl ay.Text = "USA has 250 mi llion peo pl e. "
End I f

Note In a combo box, if the user enters tex t directly rather th an selectin g from the list, the
value of the Listlndex property is - 1. This applies only to combo boxes with the Style
property set to O or 1.

The Li st property provides access to all items in the list. T hi s property co ntain s an array in
whi ch each element of the array is an item in the li st. Each ite m is represe nted in string form .
To refer to an item in the list, use this syntax:
box .List (index)

T he argument box is a reference to a list box or combo box , and index is th e position of the
item . The top item has an index of O, the nex t has an index of 1, and so on. For exa mpl e, the
fo llow ing state ment di spl ays the thi rd item (index = 2) in a text box:
Di s pla yBox .Tex t = Pop ul at i ons.List(2)

List Box Events


T he C li ck eve nt is generated every time the user selects an item in a lis t box. The use r can
selec t (highli ght) an ítem by clicking it, by using the arrow keys, or by pressing the first
Jetter of an item. Us uall y there is little need to write code for thi s eve nt. However, if yo u do,
re member that cl ic king an item always causes the Click event.
The Db! Click event is generated only when the user double-c li cks an item in the list. There
is no key board equi valent for causing this event.

Microsoft Visual Basic Programmer's Guide


138 Part 3 Appl icati on-Building Tec hniq ues

A recommended practice for list box events (especi all y when th e list box appears as part of a
di alog box) is to:
• Add a command button to use w ith the list box . The C li ck event procedure fo r thi s button
should m ake use of the list-box selec tion, carrying o ut whatever ac ti o n is appro pri ate fo r
yo ur application. ·
• Doubl e-clicking an item in th e li st should have the same effec t as selec tin g the ite m and
then clicking the command button. Thi s prov ides m ouse use rs with a ho rtc ut , ye t it
doesn' t depri ve keyboard users of esse nti al fun ction ality . T o implement thi s shortcut,
have th e Db!C li ck procedure for the lis t box call the C lick proced ure fo r the command
button.

For exampl e , suppose you have an appl icatio n w ith three co ntrols: a li st box (Popu lati o ns), a
command button (Di splayCmd) , and a tex t box (Po pDi spl ay) , as sho wn in Fi gure 11.9. Th e
lis t box is initia li zed as exp lai ned in the sectio n "P lac in g ltems in the Li st" earlier in thi s
chapter.

al Forml aa
China
India
USSR
USA

S how Pop ula tion

Figure 11.9 A list bo x, com mand button, and text bo x that work tog eth er

Microso ft Visual Basic Programm er's Guide


Chapter 11 Getting lnformation from the User 139

The Click event procedure for the com mand button di splays a different message depending
on the setting of Popul ation s.Tex t. The tex t box , PopDispl ay, is used to hold the message.
Sub Di splay Cmd_Cl ick ()
Se l ect Case Popul ati ons . lext
Case "Chi na"
PopDi splay .T ext = "Chi na ha s a bi ll i on peopl e ."
Case "I ndi a"
PopDis play .Text - " I ndia ha s over 800 mil li on peo pl e ."
Case "U SS R"
PopD is pl ay.Text - "USSR ha s 280 mi lli on peo pl e ."
Ca se "USA "
PopDisp la y.Text "USA ha s 25 0 millio n peop l e . "
End Se l ect
End Sub

You can also enable the user to displ ay the message by double-clicking one of the items in
the list; just have the Populati ons_Db! Click event procedure call the DisplayCmd_Click
procedure:
Sub Popul at i ons_DblC lick ( )
Di s pl ayC md_Click
End Sub

For more information on list bo x eve nts, see the Language Ref erence , or:

m Search Help for:


list box

Combo Box Events


A combo box recogni zes a Click eve nt when the user selects an item from its li st. It
recogni zes a Change event when any edit is made to the tex t-box portion of the combo box.
A drop-dow n li st box (a combo box wi th its Style property set to 2) doesn' t recogni ze th e
Change eve nt.
A simpl e co mbo box (Style set to 1) recog ni zes a DblCli ck eve nt just as described in the
previous section . However, a drop -dow n li st box doesn' t recogni ze Db!Click.
If the Style property of a combo box is set to either O or 2, the control recogni zes a
DropDown event whenever the user opens the li st. The user can do thi s by clickin g th e
arrow at the ri ght of the contro l, or by pressing ALT+oow when the control has the fo c us.
Responding to thi s event is useful if you wa nt to upd ate the li st j ust befare it is di spl ayed.
For more info rm ati on on combo box events, see the Languag e Refere nce, or:

m Search Help for:


combo box

Microsoft Visual Basic Programm er's Guide


140 Part 3 Application-Building Techniques

Getting Input with Scroll Bars


Although scro ll bars are often tied to text boxes or windows, sometimes yo u see them used
as input dev ices. For exam ple, severa! item s in the Windows Control Panel use scroll bars,
inc lu ding the Mouse dialog box shown in Figure 11.1 O.

Mouse

M_ouse Tracking S pee d OK


Slow Fasl

LJ
13 ,<<. -·• • LJ <> G 1 Cancel

Qouble Click Speed -


Slow Fasl
l.!J {( < D <<13
TEST 1
O liwap Lefl/Right Buttons

Figure 11 .10 Scroll bars in the Windows Control Panel

Visual Basic enab les you to use scroll bars the sam e way. With the Toolbox, yo u can create
your own hori zontal and verti cal scroll bar controls, as shown in Figure 11 .1 1.

1m Scroll Bars DD
... ..-

· · · · i- ~--.....-.tr-- Sera// box here
··· ~ ..
indicates mínimum
value .

.•.••. J~•~
· ~~-,t-- Scroll box here
l._•...
·I_IL--a'""-'-'-"'-~~'--'-"'===.:.:.i""'<'"t"""'
>...•...•... in die ates maximum
value.

Sera/! box here indicates Scroll box here indicates


111111imum value. maximum value.
Figure 11.11 Horizontal and vertical scroll bar controls in Visual Basi c

A scroll bar rcpresents an integer va lue; the scro ll box shows w here the value lies relative to
the end poi nts of the range.
When th e integer is at the minimum value, the scro ll box moves to the leftmos t position (for
horizontal scro ll bars) or the top position (fo r vertica l scroll bars) .
Wh cn th c integer is al the maximum va lu e, the scroll box moves to the rightmo st o r bottom
position . S imil arl y, a value halfway between th e bottom ancl top of th e range pl aces th e
scroll box in thc midd le of th e scroll bar.

Microsoft Visual Basic Programm er's Guide


Chapter 11 Getting lnformation from the User 141

The bas ic operati on of a scroll bar is controlled by the followin g properties.


Property Description
Min Value corresponding to the left or top of
scroll bar
Max Value corresponding to the ri ght or bottom
of scroll bar
Value Current value indicated by scroll bar
LargeChange Amount the value changes when the user
clicks the bar above or below the scroll box
SmallChange Amount the value changes when the user
clicks the arrow s at either end of the scroll
bar

Y ou can set ali of these properties at design time. At run time, the Yalue property changes as
the user adjusts the scroll bar (unless you di sable the control), but the other properti es stay
the same unless you change them from within code.
In addition to using mouse clicks to change the scroll bar value, th e use r also can drag the
scroll box to any point a}ong the bar. The resulting value depends on the position, but is
always within the range from Min to Max.

Using the Scroll Bar Value


With scroll bars, the Yalue property is an integer corresponding to positi on o f th e scale.
Suppose you have a sc roll bar named Acceleration. You calc ul ate speed by addin g th e sc roll
bar's Yalue settin g to the Speed vari able:
Speed = Speed + Ac cel e ration.Valu e

Scroll bar control s show the relative qu antity visually , but do not report the ex act qu antity to
the use r. Therefore, the user doesn ' t know exactly what value he or she is entering. One way
to pro vide thi s information is to place a text box next to the scroll bar and print out the value
whenever the scroll bar changes. The code that updates the text box should be placed in the
Change e vent procedure for the scroll bar.
For example, suppose you have a scroll bar narned Fue! and a tex t box named Fue!Readout.
The Change e vent procedure for the scroll bar displays the preci se value in Fue!Readout:
Sub Fuel _Chang e ( )
Fue l Readout. Tex t - FormaU(F uel .Valu e)
End Sub

Microsoft Visu al Basic Programmer's Guide


142 Part 3 App lication-Building Techniques

Controlling Colors with Scroll Bars


Colors provide an interesting demonstration of scroll bar controls.
With Visual Basi c forms and controls, the BackColor and ForeColor properties determin e
the background and foreground colors, respectively. The exampl e in Figure 11 . 12 enables
the user to interactively adju st the color of a text box by gettin g in stant feedback on how th e
color looks. The user adj usts three horizontal scroll bars to manipul ate the color.

11m Scroll Bar Demo ªª


Red

Green

Blue

Figure 11 .12 Using scroll bars to contro l color

The scroll bars are a 11 set to the val ucs 4 and 32 for the Smal lChange and LargeChangc
properties. Othcr properties are set as fo llows.
Control CtlName property Min property Max property
Top scrol l bar RcdBar o 255
Second scro ll bar Green Bar o 255
Third scro ll bar BlueBar o 255
Textbox Readout

The Change proccclure for each of the scroll bars responds by calling a general procedure,
DoColor, th at rccalculates the color.
Sub RedBar_Change ( l
DoColor
End Sub

Sub GreenBa r Change ( l


DoColor
End Sub

Sub BlueBar _Change ( l


DoColor
End Sub

Microsoft Visual Basic Programm er's Guide


Chapter 11 Getting lnformation from the User 143

The DoCol or procedure uses the values of the three scroll bars, combines th em with the
RGB function , and assigns the res ult to the background color of th e tex t bo x. As explained
in Chapter 13, "Creating Graphical Effects," the RGB function takes red, green, and blue
input values, each runnin g from O to 255.
Sub Do Co l or ()
Readout . BackColor - RGB (Re dBar . Value, GreenBar . Valu e. BlueBar. Valu e)
End Sub

For more information on scroll bar events, see the Language R ef erence, or:

Search Help for:


111 scroll bar
Prompting for Input with lnputBox$
You can use the InputBox$ function asan alternative technique for gettin g data . Thi s
function di splays a dialog box that contains a simple prompt m essage.
The InputBox$ function displays a standard dialog box that asks the user to enter a strin g.
When you use this function , you have little control over the com ponents of the dialog box.
For thi s reason , when you create a polished application you should generall y avo id
InputBox$ and create a dialog form instead, as described in Chapter 15 , "Creating Mu ltiple-
Form Applications."
Th~ InputBox$ function has thi s syntax:
InputBox$(prompt$ [, title$ [, default$ [, xposo/o , ypos o/o ]]])

The brackets indicate th at ali arguments but the first are optional. The comm as are argume nt
separators: You use them only to separate arguments orto show that an arg um ent i skipped.
Thus, the mínimum syntax of InputBox$ just takes one string, whi ch is inte rpreted as the
prompt$ argument.
The first three arguments are ali strings: prompt$ is the prompting tex t th at appea rs in the
text box, tille$ is the text that appears in the title bar, and defa1tlt$ is th e clefa ult res ponse
di splayed in the text box. The last two arguments, xpos and ypos, give the cli sta nce in twips
from the left edge and top edge of the screen, respectively. (A twip is 1/20 o f a point. )

Microsoft Visual Basic Progra mmer's Guide


144 Part 3 Appl icati on -Buildi ng Techniqu es

The fo ll owing state ment creates the res ult shown in Figure 11. 13.
User$ InputBox$ ( " Enter your name. " , " Input Box " )

Ente r your na me . OK
Cancel

Figure 11.13 A dia log box create d with lnputBox$

The resultin g dialo g box is modal. (A modal dial og box must be closed before the user can
switch to another forrn or di alog box.) However, the user can switch to a completely
differe nt applicati on in W indows.
When the user clicks the OK button or presses ENTER, the lnputBox$ function return s
whatever is in th e tex t box . If the user clicks Cancel, the n lnputBox$ returns an empty
string ('"' ).
For more info rmati on on how screen coordin ates work (includin g the twips measurement
system), see Chapter 12, '•Displ ay ing and Printing ln for mati on," and Chapter 13, "Creatin g
Graphical Effects." For mo re in formation on InputBox$. see the Language Ref erence, or:

m Search Help for:


inpu t

Microsoft Vis ual Basic Programmer's Guide


Displaying and Printing lnformation

It's easy to use Visual Basic to present simple messages or unformatted numbers . Many of
the applications and code fragments of previous chapters display this kind of data.
But as your applications become more sophisticated and polished, you' ll want to take
advantage of the tools Visual Basic offers for selecting fonts, formatting tables, and
changing number formats. You can even include code in your applications that automatically
adopts the number, date, and time format for the user's country (using the Format$
function) . You also can send text and graphics to the printer using the Printer object.
This chapter presents the variety of ways you have to display information . Toe main sections
· is chapter are:
emporary lnformation with MsgBox
146 Part 3 Application-Building Techniques

Displaying Temporary lnformation with MsgBox


The Visual Basic MsgBox statement is a simple and direct way to send a message to the
user. The statement causes a dialog box to be displayed with a message you specify . After
readin g the message, the user clicks an OK button to close the dialog box. Because the
dialog box is temporary , it should say something needed only briefly - perhaps an error
message, warning, or alert.
The syntax for the MsgBox statement is :
MsgBox msg$ [, type o/o [, type o/o [, tille$]]

The argument msg$ is a string that contains your message. The other arguments govern
features such as dialog box title and number of command buttons. You also can use the
MsgBox function to return a va lue indicating which button the user selected.
The following event procedure uses the MsgBox$ statement to di splay the message shown
in Figure 12. l when the user clicks a blank portion of the form .
Sub Form_Click ()
MsgBox "What we have here i s a fail ure to communicate."
End Sub

Microsoft Visual Basic

What we have here is a failure to communicate.

1 [óKj 1
Figure 12.1 MsgBox Example

This dialog box remains on the screen until the user clicks the OK button or presses ENTER.
Then Visual Basic continues execution of the next statement in the code.
The dialog box is modal. This means that users can not swi tch to another forrn in your
app lication until they first close the dialog box .
For more information on the MsgBox statement and function , see the Language Reference,
or:

m Search Help for:


MsgBox

Microsoft Visual Basic Programmer's Guide


Chapter 12 Displaying and Printing lnformation 147

Using Labels to Display Output


A !abe! control displays text that the user cannot directly change. Labels are frequently used
to identify controls such as text boxes and scroll bars that do not have their own Caption
property . Labels also are useful for displaying information that you don't want the user to
change.
The Caption property specifies what text to display. By default, the caption is the only
visible part of the label control. However, by setting the BorderStyle property to 1 (whi ch
you can do only at design time), the ]abe! appears with a border- giving ita look similar to
that of a text box. A !abe! with that setting is put to good use in the application described in
the next section .

A Temperature Converter
The application shown in Figure 12.2 converts temperatures between Celsius and Fahrenheit
temperatures. It features three labels, a text box, and two command buttons. The user enters
a temperature in the text box at the top, and it is converted to Fahrenheit or Celsius,
depending on which of the two command buttons is clicked. The converted temperaiure is
displayed in what looks like a text box labeled Output; it's actually a label that has a blank
Caption and BorderStyle set to 1.

Input: 1 Conve,I lo F. 1
Oulpul: 1 Converl lo C. 1

La beis La bel with border


Figure 12.2 Temperature Converter

The application could use a text box instead of a label to display the converted temperature.
However, information displayed in a text box can be changed by the user, which isn' t
desirable in this case. A !abe! with a border looks like a text box , but the information it
displays can't be directly changed by the user.
There is a way to prevent the user from changing text displayed in a text box: set its Enabled
propen y to False. However, once that 's done, text in it would be grayed.

Microsoft Visual Basic Programmer's Guide


148 Pa rt 3 Applicatio n-Bu ilding Techn iques

The pro perties of the application are set as follows.


BorderStyle
Control CtlName property Caption property property
First label (not used in code) In put: O (the default)
Textbox Inpu tTe mp 2 (the default)
Second label (not used in code) Outpu t: o
T hi rd !abe! OutputTemp (b lank)
Top command ToDegreesF Convert to F.
button
Bottom co mmand ToDegreesC Convert to C.
bu tton

T he Click procedure fo r ToDegreesF converts a Celsi us temperatu re in the InputTemp text


box to a Fahrenheit temperature:
Sub ToDegreesF_Cli ck ()
Oeg r eesC - Val(InputTem p.Text)
DegreesF - (Deg r eesC * 9/5) + 32
Out putTe mp. Ca pt i on = Format$(DegreesF)
End Sub

As wi th many of the other exarnples in this manual, the proced ure above fo ll ows a standard
approac h: Convert the characte rs in a text box to a numeric value. pe rform ca lc ulat ions on
the value, the n convert the val ue to a tex t string and display it. The Click procedure fo r
ToDegreesC takes the sam e approach , but performs the reverse calc ulation :
Sub To DegreesC_Click ()
Deg reesF = Val(InputTemp.Text )
DegreesC - (DegreesF - 32) * 5/9
OutputTemp.Caption - Format$(DegreesC)
End Sub

Note that in both procedures DegreesC and DegreesF are two local vari ab les represe ntin g
Ce lsius anct Fahrenhe it quantities, respectively. Because th ey are not ex plicitl y declared ,
they have the default data type, Single.
For more info rm ati on on the label control, see th e Language Reference, or:

m Search Help for:


la be l

Microsoft Visual Basic Programmer's Guide


Chapter 12 Displaying and Printing lnformation 149

Setting Characteristics of Text (Fonts)


All of the objects that can display text support the font properties, which determine the
visual characteristics of the text itself, including:
• Letter style (font)
• Size
• Special characteristics such as: bold, italics, underline, or strikethrough

Most types of objects can display sorne kind of text, including forms, text boxes, labels, list
and combo boxes, and any control with a Caption property. (This includes command
buttons, labels, check boxes, and option buttons.) In addition, all of the font properties apply
to the special Printer object introduced later in this chapter.
The exact effect of the font properties depends on the technique used to display text:
• If the text is specified by a property (such as Text or Caption), then a change to a font
property applies to the entire contents .
Labels, text boxes, frames, buttons, check boxes, and all the file-system controls use a
property to specify text. None of them supports the Print method.
• If the text is displayed by the Print method, a change to a font property affects
subsequent uses of Print, but has no effect on previously printed text.
Only forros and picture boxes support the Print method.

Consequently, text boxes and labels cannot display text that mixes fonts. If you need to mix
fonts (for example, you want to make sorne words bold but leave others in normal style),
then create a picture box and use the Print method to display text. The next section ,
"Printing to Forms and Picture Boxes," explain s how to use Print.

Microsoft Visual Basic Programmer's Guide


150 Part 3 Applicatioíl-Buildiílg TechíliQues

The six font prope11ies are:


Property Type Description
FontName String Specifies name of font (for
example, "Modem ,"
"Courier," "Script").
FontSize Integer Specifies font size in points
(6 toan inch when printed) .
FontBold lnteger (Boolean) If True, the text is bol d.
Fontltalic Integer (Boolean) lf True, the text is italic .
FontStrikethru Integer (Boolean) If True, Visual Basic strikes
throu gh the text (for
example, t{}X-l) .
FontUnderline Integer (Boolean) lf True, the text is
underlined.

An additional font property, FontTransparent, is supported for form s and picture boxes only .
The settings available for each of the properties are listed in the Settings box at the middle of
the Properties bar. lf you use a setting from the list, you don ' t have to worry about picking
an unavailable size or typing a font name incorrectly .
You can set any of the font properties at design time (by using the Properties bar) or at run
time. For example, th e followin g statements set various font properti es for a control named
Labell :
Labell . Foílt Name = "M odern" Chaílge foílt to Moderíl.
Lab ell . Fo ntBold = - 1 Tur íl Oíl bold.
Labell.Foíltitalic = - 1 Turn Oíl italics.
Lab ell . Foílt Uíld er liíl e = 0 ' Remove underliíl e.

The order of selection is import an!. becau se not all fonts support ali font variations (bold,
itali c, and so on). Set th e Font Na me property first. The Boolean font properties are not
mutu ally exclusive. They ali can be se t to True, all set to False, or set in any combination of
True and False.
For more information on fo nt properties, see the Language Reference, or:

m Search Help for:


foílt

Microsoft Visual Basic Progra mmer's Guide


Chapter 12 Displaying and Printing lnformation 151

Printing to Forms and Picture Boxes


In addition to placing strin gs in tex t boxes, yo u also can make text appear directly on a form .
When you print to a form , the tex t appears behind any controls that have been placed on the
form. Therefore, printing to a form usually works best with a blank form specifically created
to hold the text.
You also can print text to a picture box control. A picture box is a simple rectangular area
into which you can load or copy a bitmap picture, draw graphics, or print tex t. One
advantage to using a picture box is that it gives you a well-defined area to display text and
graphics; the area is separate from other controls on the same form .
To print on a form or picture box, use the Print method, preceded by the name of a form, a
picture box , or the Printer object. The sy ntax is:
[obj ecl .JPrint [expressionlist ][ { ; 1 , }]

The object is optional; if omitted, the Print method applies to the form to which the code is
attached (the curren t forrn). Por example, the following statements print different messages
to MyForm, Picture 1, and the current form:
MyForm. Pr i nt "Thi s is a form."
Picturel.Print "This is a picture box."
Print "This i s the current form."

Multiple items in the expressionlist must be separated by commas or semicolons or both , as


explained in the next section.
If the form or picture box is too small to display all the text, the text is cut off at the ri ght and
bottom edges of the object. The form or picture box does not scroll .

Combining ltems on a Line


The items you print can incl ude property values, constants, and variables (ei ther string or
numeric). The Print method translates any numeric items into their text equivalent and
inserts a trailing and leadi ng space.
Use a semicolon (;) ora comrna (,) to separate one item from the next. If you use a
se micol on, Visual Basic prints one item after another, without intervening spaces. If you use
a comrna, Visual Basic skips to the next tab colurnn.
For example, the fo llowing statement prints to the current form:
Print "Th e value of X is"; X; "and t he valu e of Y is" Y

If X contains the value 2 and Y contains the value 7, the statement produces this output:
The value of X is 2 and the value of Y is 7

Microsoft Visual Basic Programm er's Guide


152 Part 3 Application-Building Techniques

By default, each Print method prints the text and moves to the next line. If there are no
items, Print simply skips a line. A series of Print statements (for a picture box named
Picturel ) automatically uses separate lines:
Picturel.Print "Thi s is line l."
Picturel.Print "Thi s is line 2. "

Yet by placing a semicolon at the end of the first statement, you cause the output of the next
Print statement to appear on the same line:
Pi cturel. Pri nt "Th i s all appears ";
Picturel.Print "on the sa me line."

Printing at Specific Locations


Yo u can control where Print output is placed by using the Cls (clear) method and by setting
the drawing coordinates of the given form or picture box. The drawing coordinates
determine where the next Print or graphics operation will start sending output.
The Cls method erases all text placed in the object with previous Print methods (as well as
graphics) and resets the drawing coordinates to the (0,0) coordinates, which by default are at
the upper-left comer. For example, these statements clear Picturel and the current forrn:
Picturel. Cls
Cls

You also can set drawing coordinates directly by setting the CurrentX and CurrentY
properties for any given forrn or picture box. For example, these statements reset the
drawing coordinates to the upper-left comer for Picture 1 and for the current fonn:
Picturel.CurrentX = 0
Picturel.CurrentY = 0
CurrentX = 0
CurrentY = 0

Any new text you print is overlaid on top of whatever text and graphics are already there . To
erase text selectively , draw a filled-in box using the background color, as explained in
Chapter 13, "Creating Graphical Effects."
By default, forms and picture boxes use a coordinate system in which each unit corresponds
to a twip (1,440 twips equ al an inch, and approximately 567 twips equal a centimeter). Thi s
is a logical twip - the length of an object that is one twip long when output on the printer.
For more information on coordinate systems, see Chapter 13; the Language Reference; or:

m Search Help for:


coordinate system

Microsoft Visual Basic Programmer's Guide


Chapter 12 Displaying and Printing lnformation 153

Using the TextHeight and TextWidth Methods


You can use the TextHeight and TextWidth methods to determine coordinate settings.
TextHeight retums the height of a line of text. The syntax is:
[object.] TextHeight(stringexpression$)

If the string contains embedded carriage-return characters (Ch r $ ( 13 ) ) , then the text
corresponds to multiple lines, and TextHeight returns the height of the number of Iines of
text contained in the string. If there are no embedded carriage returns, TextHeight always
returns the height of one line of text.
One way to use this method is to set the CurrentX property to a particular line. For example,
the following statements set the drawing coordinates to the beginning of the fifth line:
Current X TextHeight("sampl e " ) * 4
CurrentY = 0

Assurning there are no carriage returns in the sample text, you would use this syntax to set
CurrentX to the Nth line:
CurrentX = [object .] TextHeight(sampletext) * (N - 1)

The brackets indicate that object is optional; if object is omitted, the method applies to the
current form . The object can be either a form or a picture box.
The TextWidth method returns the width of a string, taking into account the object' s font
size and style. This method is useful for deterrnining right alignment; if a line of text is about
to run off the right edge of the form, you skip to the next line by using the Print method
with no arguments. The TextWidth method helps you determine if the width of the string is
larger than the width of the form (or picture box) .
For example, the following Sub procedure takes a word , contained in the string S, and
determin es whether to print the word on the current line or to advance to the next line first :
Sub PutAWord (S As String)
If Te xtWidth(S) + CurrentX >= Sc aleWidth Then
Print
End I f
Print S; " " . .
End Sub

The ScaleWidth property gives the interna! dimensions of the form - the width of the area
within the borders of the frame . (As you ' ll see in Chapter 13, "Creating Graphical Effects,"
ScaleWidth also can be used to set the coordinate system .) Forms , picture boxes, and most
other types of objects have both a ScaleWidth anda ScaleHeight property.
For more information on the TextHeight and TextWidth methods, see the Language
Reference, or:

m Search Help for:


text

Microsoft Visual Basic Programmer's Guide


154 Part 3 Appli cation-Building Technique s

Printing Tabular Data


The Print method offers two ways to print tables of information : You can use preset tabs or
you can set up your ow n tabs. The preset tabs provided by the Print method are especially
easy to use. If the data yo u' re printing is longer than about 13 characters, however, you
should set your ow n tabs.

Using Built-ln Tabs


The eas ies t way to print tab les is to use the print zones built into Visual Basic. Each print
zone is 14 columns wide, where a column is the average size of a character in the font and
font size you spec ify.
When you insert a co mm a between two items in a Print method , the second ítem is printed
starting at the next print zone. The fo ll ow ing statements produce the outpu t shown in F ig ure
12.3.
Pi cture l .Fo ntName = "System"
Picturel.FontSize = 10
Pi cturel. Pri nt " Fi rst name", "Last Name", "Ph one number"
Picturel.Print
Picturel.Print "Jonathan", "Vanderbilt ", "555 - 4444"
Pi cturel. Pri nt "Arl ene " , " Li 11 egard " . "555 -7891"
Pi cturel .Print "Joanne " , "Buchanan " , "99-11-12345 "

11
First n ame Last Name
Forml
Phone numb er
aa
Jon athan Vand erbilt 555- 4444
Arle ne Lill ega rd 555-7891
J oa nn e Buchanan 99 -11 -12345

Column O Column 14 Column 28


Figure 12.3 Using built-in print zones

Figure 12.3 sho ws a l 0-point System fon t. Like most Windows fonts, System is a
proporti o nal fon t and includes characters of vary ing widths. In this example, each print zone
has th e same width as 14 average System 10-point charac ters . When settin g up tables,
remember that letters such as "W" take upa little more than one column, and letters like " i"
take upa little less than one column.

Setting Up Vour Own Tabs


For more control over the appearance of tables, yo u can set your own tab position s. To
specify a tab positi o n, call the Tab fu nction and include the position as one of the items in a
Print state ment. The sy ntax is:
Tab (co lu mn) ;

Microsoft Visual Basic Programmer's Guide


Chapter 12 Displaying and Printing lnformation 155

For example, the following statements print a message in the System font starting at column
5. Each column is the size of an average character in the font you choose:
Picturel.FontName = " System "
Pictur el.Print Tab(5); " This me ssage starts in column 5."

Figure 12.4 shows a table printed to a form. The first tab, at column 2, indents the Iines
slightly from the left edge of the picture box. The tab at column 22 sets the position for the
"Description" heading and the text printed below it.

!ZD Forml aa
Fi lename De scription

SUMMARY.TXT Overview of project


TESTING.TXT Testing plan
USERDOC.TXT Us er manual

Column(2) Column(22)
Figure 12.4 Using tabs in a table

The code that prints thi s table on the form is:


Picturel . FontName " System "
Picturel . FontSi ze = 10
Picturel.Print
Picturel.Print Tab(2); " Filename "; Tab(22); "Description"
Pi ct ur e l.Print
Picturel.Print Tab(2); " SU MMARY.TXT"; Tab(22); "Overview of project"
Picturel.Print Tab(2); " TESTING.TXT"; Tab(22); "Testing plan"
Picturel.Prin t Tab(2); "USERDOC.TXT"; Tab(22); " User manual"

For more information on the Tab function and using it with the Print method , see the
Language Reference, or:

Search Help for:


111 tab

Microsoft Visual Basic Programmer's Guide


156 Part 3 Appli cation -Buil ding Techniques

Formatting Numbers, Dates, and Times


Vi sual Bas ic g ives you great flexibility in displaying number form ats as well as date and
time fo rmats. Yo u can easily di splay international formats for numbers, dates , and ti mes.

Number Formats
The Format$ function , like the Str$ function , converts numeric values to strings . But with
Format$, you have more control over the appearance of the string . For example, you can
speci fy th e numbe r of decimal places, leading or trailing zeros, and currency formats.
The syntax of the the Format$ fun cti o n is:
Format $( 1111meric-expression l,frnt$ ]) ;

T he argumcn t 11umeric-expressio11 spec ifi es a number to con ve rt, andfmt$ is a string made
up of sy mbo ls th at show how to format the number. The most commonly used symbol s are
listed in th e fo ll owin g table.
Symbol Description
o Digit placeholder; prints a trailing or leadin g
zero in thi s positi o n if appropriate .
# Digit placeholder; never prints trailing or
leading zeros.
Decimal place holder.
Thousands se parato r.
- + $ ( J :--pact' Literal character; di spl ays each o r th ese
charac ters exac tl y as typed into th e form al
string .

Severa! examples are li s tecl be lo w. Th ese number con vers io ns ass um e th at the country in thc
Wind ows Con tro l Pane l is se t to "U nit ed States.'·
Format$ example Result
Format$(83 J 5.4, "00000.00") 083 15.40
Format$(83 l 5.4 ... #####.##") 83 15 .4

Form at5í(8] 15.4 ... ##.##0.00") 8.3 15.40


Format$(3 l 5.4 ;'$##0.00") S3 15 .-+0

Format$ s uppo n s man y other spec ial characters. For more inform ation , see the Lang11age
Ref erencl:'. or:

m Search Help for:


Form al$

Microso ft Visual Ba sic Programmer's Guide


Chapter 12 Displaying and Printing lnformation 157

The sy mbol for the decim al separator is a period (.) and the sy mbol for the thou sands
separator is a comma (,). But the character that' s actually di splayed as a decimal separator or
a thousands separator depends on the country set in the Windows Control Panel.
Country Format$ syntax Result
Sweden Format$(7300, "0,000.00") 7.3 00,00
United Kingdom Format$(7300, "0,000.00") 7,300.00
Germany Format$(7300, "0,000.00") 7.300,00

Date and Time Formats


To print date and time formats , use the Format$ function with sy mbol s representing date
and time. The examples shown print the current date and/or time usi ng the Now function .
Thesc cxamp lcs assume that the co untry se l in the Wind ows Co ntrol Panel i~ ··u nit ecl
States."
Format Result
Format$(N ow, " m/d/yy") 7/28/91
Format$(Now, "dddd , mmmm dd, yyyy") Sunday, July 28, J 991
Format$(Now, "d-rnmm") 28-July
Format$(Now, "mmmm-yy") July-91
Format$(Now, "hh:rnm AM/PM") 07: 18 AM
Format$(Now , "h:mm :ss a/p") 7: 18:00 a
Fo rm at$(Now, "d-mmmm h:mm") 28-Jul y 7 : 18

By usi ng the Now function with the format "ddddd" and "ttttt," yo u can print th e current
date and time in a format appropriate for the country set in the Windows Control Panel.
Country Format$ syntax Output
Sweden Format$(Now, "ddddd ttttt") 90- 12-3 1 18.22 .38
United Kingdom Format$(Now, "ddddd ttttt") 12/3 1/90 18:22.38
Canada Format$(Now , "ddddd ttttt") 90- 12-3 1 18 :22:38
United States Format$(Now, "ddddd ttttt") 12-31-90 6:22:38 PM

For more information on date and time funct ions, see the Language Referen ce, or:

m Search Help for:


now

Microsoft Visua l Basic Programmer's Guide


158 Part 3 Appli cation-Building Techniques

Sending Output to the Printer


Visual Basic provides two ways to print your output to the printer (this is the default system
printer that the user spe~ifies in the Control Panel) :
• Send text directly to the printer.
• Produce the output you want on a form and then print the form .

Sending Text Directly to the Printer


To send text directly to the printer, use the Print method and specify Printer as the drawing
object. The syntax is :
Printer.Print 1ext [;]

The Prinler object supports ali of the graphics methods presented in Chapter 13, "Creating
Graphical Effects," and can be used to display lines, circles, and points .
The Printer is the name of an object in Visual Basic that has all the font properties described
earlier. For example, the following statements send bold Modem type to the printer:
Printer .Fo ntName = "Modern"
Printer.FontBold = -1
Printer .P rint "Bold Modern type appears on printer."

Because these statements set FontBold to True (-1), subsequent statements also print bold
text on the printer unless you turn off the bold font :
Printer.FontBold = 0

You can set CurrentX and Current Y properties for the Printer object, justas you can with
forms and picture boxes. With Printer, these properties determine where to position output
on the curren t page. Thus, the following sta tements set drawing coordinates to the upper left
of the current page :
Printer.CurrentX 0
Printer.CurrentY = 0

Microsoft Visual Basic Programmer's Guide


Chapter 12 Displaying and Printing lnformation 159

When -printing longer documents, you can specify where you want a new page to begin
using the NewPage method. When you are fini shed creating a print document, specify the
EndDoc method. This advances the page and causes all pending output to be sent to the
spooler. (If you return to design time, Visual Basic issues an EndDoc call automatically.)
For example:
Printer.Print "Thi s is pag e l. "
Printer.NewPage
Printer.Print "Thi s is page 2 ."
Printer . EndDoc

After you use the EndDoc method, you can start printing another document. The first page
of the new document is assigned page number 1. This page number isn't automatically
printed, but Visual Basic tracks the page .number internally. You can access this number by
using the Page property . For examp lc, if yo u wa nt to print a header at thc top of cve ry pagc
of a budget report:
Header$ = "Monthly Budget Summary"
Printer.Print Header$ + Printer.P age
Printer.NewPage
Printer.Print Header$ + Printer . Page
PageNo = Printer.Page
MsgBox "Y ou r document contains " + PageNo + " pages. "
Printer.EndDoc

Printing Forms
Yo u also can send output to the printer by produci ng the output you want on a form , and
then printing the entire form using the PrintForm meth od . This method is very simple. You
can precede PrintForm by the name of a form. lf you omit the form name, Visual Basic
prints the current form. The sy ntax is:
[form.]PrintForm

PrintForm prints the entire form, even if part of the form is not visi ble on the screen. If a
form contains graphics, however, the graphics print only if the form's AutoRedraw property
is set to True (-1).
The PrintForm method always sends pixels on the form directly to the printer. As a
consequence, you may not get the hi ghest resolution when you use PrintForm . For
example, you could send text to a printer by first printing it on a form , then calling
PrintForm :
Print "Here is so rne text . "
PrintForm

Mic rosoft Visual Basic Programmer's Guide


160 Part 3 Application-Building Techniques

However, if the printer has higher resolution than the monitor, then thi s statement prints the
same text with better clarity:
Printer.Print "Here is sorne text."

For more information on the PrintForm method, see the Language Reference, or:

m Search Help for:


PrintForm

Mic rosoft Visual Basic Programmer's Guide


Creating Graphical Effects

Animated, graphical applications are among the most appealing and exciting to the user.
But with traditional programrning environments, they are difficult to create.
Not so with Visual Basic, which provides severa! ways to produce graphical effects in your
applications. You can move objects around on the screen , make them appear and di sappear,
even change their size - all with simple and easy-to-leam statements. The Visual Basic
language also provides statements that enable yo ur applications to draw circles, lines, boxes ,
and other shapes.
With th e~c fca tures yo u' ll be ab lc to writc game::,, animatcd cffcct -, co lorful ::, imulatiom,, or
any app lication where graphical effects could enhance the user's presentation .
This main sections in this chapter are:
• Adding Pictures to Your Forms
• Moving Controls Dynarnically
• Resizing Controls Dynarnically
• Showing and Hiding Controls
• Adding and Removing Controls
• Settin g an Object's Coordinate System
• The Fundamentals of Drawin g
• Drawi ng Lines and Shapes

• •• • •
••••
•• ••••
•• ••• •

_,...,,•~.
_,/",:.·,•.J
.. -:· .-?~
• • •
••••
. .o:--.,.
.{'.....·, ·•.•- J
~:::•:. ->·
¡¡:-·_••-~/
4-:i.--
162 Part 3 Application-Building Techniques

Adding Pictures to Vour Forms


Pictures can be displayed in two places in Visual Basic applications, on a form orina
picture box. Previous chapters have described how to use picture boxes to group option
buttons and to contain output from the Print method, but you' 11 probably use picture boxes
most often to hold a picture.
Visual Basic can read picture files in any of the following standard formats :
• Bitmap. A bitmap has the file extension .BMP.
• !con. An icon has the file ex ten sion .ICO.
• Metafile. A Windows merafile has the file extension .WMF. Only files compatible with
Microsoft Windows 3.0 can be loaded.

These files can come from Microsoft Windows Paintbrush (incl uded with Windows 3.0),
other graphics programs, or clip-art libraries.
You use different techniques for adding a picture to a form or picture box, depending on
whether you do it at design time or run time .

Adding a Picture at Design Time


There are two ways to add a picture at design time :
• Load a picture into a form or picture box from a picture file:
In the Properties bar, select Picture from the Properties li st box and click the three dots at
th e right of the Settings box. Visual Basic di splays a dialog box, from which yo u selecta
picture fil e.
If you set the Picture property for a form , the picture you select is di splayed on the form ,
behind any controls you ' ve placed on it. Likewise, if you set th e Picture property for a
picture box, the picture is displayed in the box, behind any con trol s you place on it.
• Paste a picture onto a form or into a picture box:
Copy a picture from another app li cation (such as Windows Paintbrush) onto the
Clipboard. Return to Visual Basic, se lec t the form or picture box, and choose Paste from
the Edit menu .

Once you've set the Picture property for a form or picture box (either by loading a picture
or pasting one), the word displayed in th e Settings box is "(Bitmap)," "(Icon) ," or
" (Metafile) ." To change the setting, loador paste anot her pi cture. To set the Picture property
to "(None)" again, double-click the word displayed in the Settings box and press the DEL
key.

Microsoft Visual Basic Programmer's Guide


Chapter 13 Creating Graphical Effects 163

Adding a Picture at Run Time


There are two ways to add a picture at run time:
• Use the LoadPicture function to specify a filename and assign the picture to the Picture
property.
The following statement loads the file CARS.BMP into a picture box named DisplayBox
(you name a control by setting its CtlName property) :
DisplayBox.Picture - LoadPicture (''c:\picts\cars.bmp")

Y ou can load a new picture file onto a form or into a picture box whenever you want.
Loading a new picture completely replaces the existing picture, although the source fil es
of the pictures are never affected.
• Copy a picture from one object to another.
Once a picture is loaded or pasted onto a form or into a picture box, you can assign it to
other forms or picture boxes at run time . For example, this statement copies a picture
from DisplayBox to another picture box named DisplayBox2:
DisplayBox2.Picture = 0isplayBox . Picture

You can both load a picture and assign it to another object by using both the previous
statements within one procedure:
DisplayBox.Picture = LoadPicture ( " c : \p i cts\ca rs.bmp")
DisplayBox2.Picture = DisplayBox.Picture

Note If you loador paste pictures from fil es at design time, the pictures are saved and
loaded with the form. When you create an .EXE file , you don't need to give your users
copies of the picture files; the .EXE file itself co ntains the images. In contrast, to load
pictures at run time with the LoadPicture function, you mu st supply the picture fil es to your
users along with your application. For this reason it's often better to loador paste pictures at
design time. Your application can then copy pictures from one object to another, as
described above.

Another way to set the Picture property is to use the Clipboard object. For more information,
see Chapter 18, "Interacting with the Environment"; the Language Reference; or:

m Search Help far:


Clipboard object

Moving and Sizing Pictures


If a form or picture box is moved (at design time or run time), its picture automatically
moves with it. If a form or picture box is resized so it 's too sma ll to display a picture, the
picture gets clipped at the right and bottom . A picture is al so clipped if you loador copy it
onto a form or into a picture box that is too small to display ali of it.

Microsoft Visual Basic Programmer's Guide


164 Part 3 Application-Building Techniques

If you want a picture box to automatically expand to accommodate a new picture , se t the
AutoSize property for the picture box to True (-1 ). Then when a picture is loaded or copied
into the picture box at run time, Vi sual Basic automatically expands it down and to the right
enough to display ali of the picture. (The picture box is visible only up to the edges of the
form where it resides, however; if the image you load is larger than that, it appears clipped
because the form size doesn ' t change.)
Y ou also can use the AutoSize property to automatically shrink a picture box to retl ect the
size of a new picture .
Forms do not have an AutoSize property, and do not automatically enlarge to display ali of a
picture.

Selecting Art for the Picture Control


\\.heredo you gel pictuie l°ik:,.' 11 ) O U wa.nt ico11:,, you can use the lcon Library incluJed
with Visual Basic, or create them yo urself with a program such as Microsoft Windows SDK
Paint. You can create .BMP file s with Microsoft Windows Paintbrush. Or, yo u can bu y a
clip-art collectio n that includes bitmap or icon files , or metafiles.
The Visual Basic Icon Library includes a set of icons organized into these groups:
• Arrows and pointers
• Communication (networking. phones, printers, servers)
• Computer (computers, disk drives, diskettes, keyboards, mice, Windows fo lders)
• Flags
• Mail (mailboxes, envelopes)
• Office (card fil es. charts. file cabi nets, folders, graphs, paper clips)
• Traffic sign s
• Writing (books, notepads, pens. pencils)
• Miscellaneous (c locks. first aid signs, locks and keys , phases of the moon , and so on)

Figure 13 .1 shows so rn e sa mpl es of the Icon Library. To see all of the pictures in the Icon
Library, refer to Appendix B, '·Jcon Library," or use the IconWorks sample applicati on
incl uded with Visual Bas ic.

11 forml . Da

[Q m 1

~ ~
m ~ ii .
cm
Figure 13.1 Samples from the Visual Basic lean Library

Mic rosoft Visual Basic Programmer 's Guide


Chapter 13 Creating Graphical Effects 165

Toggling Between Two lcons


Sorne of the icons in the Icon Library can be used in pairs. For instance, there are two
mailbox icons in the lcon Library, one with its flag down, and one its flag up, as shown in
Figure 13.2. By switching between the two (also called "toggling"), you can create a little
animation at run time and also enable your user to easily see the status of mail.

mi Forml aa

Figure 13.2 lcons MAIL16A.IC0 and MAIL16B.IC0 from the lean Library

To create a toggling effect, first draw three picture boxes on a forro at design time. Set th e
BorderS tyle property to O for the first one, and name it Mailbox. Name the other two
NoMail and Mai!Here. Set the Picture property for NoMail to the mailbox icon with its flag
down (the icon file is named MAILI6A.ICO) . For MailHere, set the Picture property to th e
icon with its flag raised (MAIL16B.ICO). Set the Visible property to False (0) for both
Mai!Here and NoMail ; you want to use the images stored in those controls, but you don ' t
want them to be visible on the form.
lf you are using mailbox icons in a mail application, you probably want a Form_Load
procedure that checks to see whether there are messages awaiting the user, and sets the icon
accordingly. In this case, use a Form_Load procedure that sets the Picture property for th e
Mailbox control to the ico n with the flag down :
Sub Form_ Load ()
Mailbo x.Pict ur e = NoMail.Picture
End Sub

Use thi s code for the Mailbox_Click event procedure:


Su b Mailbo x_ Click ()
If Mailbox . Picture = NoMail.Picture Then
Mailbox.Picture = MailHere.Picture
Else
Mailbo x.Pict ure = NoMail.Picture
Encl I f
End Sub

Now when you run the application and click the Mailbox picture box, it switches betwee n
the icon with its flag down and the one with its flag up.
For more information on the picture box control and using graphics in your app li cations:

111 Search Help for:


picture box a See Tutorial Lesson:
"Creating Custom Applications"

Microsoft Visual Basic Programmer's Guide


166 Part 3 Appli catio n-Buildin g Technique s

Moving Controls Dynamically


With Visual Basic, one of the easiest effects to achieve is moving a control at run time. You
simpl y change th e settings for the Left and Top properties with the Move method.
Figure 13.3 shows the relationship between the Left and Top properties and the actual
locati on of a cont ro l.

' Top
... .... ·· · ····-·· 1- - -¡A
- Bu-tt-on- !- - - - - - -- - - - +-

Figure 13.3 Left and Top properties

The Left property is the distance between the upper-left corner of the control and th e left
side of the for m. The Top property is the distance between the upper-left corner of the
control and the top of the form.
You can move a contro l by changing the settings of its Left and Top properties with
assignme nt statements such as these:
Textl.L ef t = Text l.Left + 200
Textl.T op = Textl.Top - 300

Howeve r. tha t woul d produce a jerky effect, as the control first moves hori zo ntall y and th en
vert ically. In contras t, using the Move meth od produces smooth di agonal movement. The
syntax for the Move method is:
fobjec1 .]Move left [, top[, width [, height]]]

The ohject is th e form or control to be moved. lf object is omitted, the method appli es to th e
current fo rm ; th at is, th e current form gets moved. The arguments left and top are th e new
settings fo r th e Left and Top properti es of object, while width and height are new settin gs fo r
its Wi dth and Height properties. Onl y left is required, but to specify any oth er argum ents,
yo u mu st spec ify ali arguments that appear in the syntax before the argument yo u wa nt to
<; rc ci f\ ·
The fol lowing state ments move th e contro l named Tex tl :
Textl.Move 100. 200
Textl.Move Textl.Left + 100 , Textl.Top + 100

The first statement moves it to the coordin ates ( l 00, 200). The second statement moves it
relati ve to its current position .

Microsoft Visual Basic Programmer's Guide


Chapter 13 Creating Graphical Effects 167

By default , ali Visual Basic movement, sizing, and graphical-drawing statements use a unit
of one twip. A twip is 1/20 of a printer's point (1,440 twips egua] an inch, and 567 twips
egua! a centimeter). These measurements apply to how large an object will be when printed .
Actual physical distances on the screen vary according to the monitor size.
In the section "Setting an Object' s Coordinate System" later in this chapter, yo u' 11 learn how
to select units other than twips. For now, just use the default scale.

Example of Control Movement


Movement of controls is useful in many applications, including games and business
applications. This section shows a simple use of control movement: Click the command
button , and the control moves diagonally to the right and to the top .
The interface consists of a form with one command button , as show n in Fi gure 13.4.

ID Forml DD

\Click H ere j

Figure 13.4 A button that moves when clicked

The name of the control is MyButton . The Caption property is set to "Click Here."
There is one event procedure, for the command button 's Click event:
Su b MyButt on_Click ()
MyButt on. Move MyButton.Left + 500 , MyButton.Top - 500
·End Sub

You ca n ex periment with different amounts by building this application and then ed itin g the
line of code . lnstead of 500 twi ps , try 50, 700, or 1,000.
For more information on the Move method, see the Language Reference, or:

m Search Help for:


Move

Microsoft Visual Basic Programmer's Guide


168 Part 3 Applic ation -Building Techn iques

Resizing Controls Dynamically


In a Visual Basic application, you can change the size and shape of a control or form at run
time, justas you can change its position .
The following three properties affect size.
Property Description
Hei ght Height of the object expressed in twips.
Width Width of the object expressed in twips.
AutoSize If True, causes Visual Basic to always adjust
th e control dimensions to the size of the
contents .

Hei ght and Width apply to all forms and all controls except timers and menus, while
AutoSize applies only to labels and picture boxes.
In thi s example, a _command button named Command1 grows larger each time the user · -
clicks it:
Sub Co mmandl _Click ()
Co mmandl . Height = Commandl.Height + 300
Co mmandl . Width = Commandl. Wi dth + 300
End Sub

Showing and Hiding Controls


Objects th at appear and disappear can add interesting visual effects to your Vi sual Basic
ap plicati on. This capability is especiall y useful in games or simul ati ons, in which you might
need a new object to enter onto th e scree n.
This section explains how to show and hide existing controls, and the next sec tion explains
how to add new controls. For informatio n on how to show or hide forms at run time (using
the Show and Hide methods), see Chapter 15, "Creating Multiple-Fo1m Applications"; the
Language Reference; or:

m Search Help for:


show

Al i co ntrol s exce pt tim e rs have a Vi sihl e property . Setting th e Vi sible propert y to Fa lse (0)
makes the co ntrol "disappear,.. eve n thou gh it is still loaded in memory . For exampl e, thi s
statement makes a co ntro l named Text I disa ppear:
Textl. Vi sible = 0

Microso ft Visual Basic Programmer's Guide


Chapter 13 Creating Graphical Effects 169

The next statement makes the control reappear by setting the Visible property to True (- 1).
Because Textl was not actually deleted from memory , it automatically reappears with ali its
old settings (unless you've changed sorne of the property settings in the meantime).
Textl.Visible - - 1

You also can use a single statement to hide a control if it's visible and show it if it's hidden .
The statement takes advantage of the fact that the Visible property is Boolean-it' s either
"on" or "off' - and toggles it between the two settings:
Sub Commandl_Cli ck ()
Textl.Visible - Not Textl.Vi s ible
End Sub

You can use similar code to toggle othcr Boolean properti es.

Adding and Removing Controls


The previous section explained how to hide and show existing controls. You also can add
and remove controls at run time using the Load and Unload statements. However, the
control to be added must be an element of an existing control array. Control arrays were first
introduced in Chapter 1O, "Respondin g to Commands."
A control array is a group of controls that share the same name and type. They also share the
same event procedures, but they are physically separate, ~nd each control has its own
property settings. Figure 13.5 shows a contro l array of three command buttons.

i:=I (/ Forml aa

8 Cmd(O)
•• Cmd(l ) Cmd(2)
Figure 13.5 A control array ofthree command buttons

The Index property distinguishes one element of the control array from another. When one
of the co nt ro ls in th e arra y recogni zc1., an e, cnt, Vi sual Basic ca lIs a com mon event
procedure and passes an additional argument (the Index property) to identify wh ich of the
controls actuall y recognizes the event.
For example, the first line of the Cmd_Click procedure is :
Sub Cmd _Click (Index As Integer)

If Cmd(O) recognizes the event, Visual Basic passes O as th e Index argument. If Cmd( l)
recognizes the e vent, Visual Basic passes l as the Index arg umen t.

Microsoft Visual Basic Programmer's Guide


170 Part 3 Application-Building Techniques

A control array has at least one element , but can grow to as many as 255. (There is a limit to
255 controls to a form .) Elements of the same control array have their own property settings,
but share the same code. Think of an elemen t asan "instance" of the array. When yo u load a
new element of the control array , the new e lement inherits any pre-existing event
procedures .
Without the control array mechanism, dynamically creating new controls is not possible. A
completely new control does not have any event procedures. Control arrays solve thi s
problem, because each new control uses the cornmon event procedures already written for
the array.
You can create a co ntrol array in one of two ways at design time:
• Set the Index property. usin g the Properties bar.
• Give two control s th e same name. (They mu st have the sa me type .) Vi sual Bas ic
automatically creates a control array and gives these controls the indexe O and 1.

The procedure in the next sec tion uses a control array to create any number of new controls.

Creating a Control Array


To create a control array, draw a text box, and set its CtlName property to TextBoxes and its
Index property to O. The following For loop adds ten new instanc"es of the text box ,
assigning them indexes ran gin g from I to 1O:
Dim I As Integer
Far I = 1 To 10
Load TextBoxes(I )
TextBoxes(I). Visible = -1
Next I

When yo u load a new clemcnt of a co ntrol array. ali the property settings exce pt for Vi sibl e,
lndex , and Tabindex are copied from th e lowest ex isting element in the array. As a re sult ,
the previous code makes al I th e control s the same size, and stacks them ali in one place.
A lso, because new control s are crea ted with the Visible property set to False (zero), none of
th e m is visib le (even thou gh th e text box you've drawn is).
The following code ass um es you · ve created a text box named Textl and set its Index
property to O. U pon loading of the form, the procedure loads new text boxes, places them
apart vertically , and turn s on the Visib le property of each.
Sub Form Load()
Far I = 1 to 10
Lo ad Textl ( I )
Textl(I).Top = Textl(I - l).To p + 500
Textl(I).Vi s ibl e = - 1
Textl(I).Text = "Textl( " + Format(I) + " ) "
Next I
End Sub

Microsoñ Visual Basic Programmer's Guide


Chapter 13 Creating Graphic al Effects 171

Note Visual B asic generates an error if you attempt to use the Load statement with an
index number already in use within th e array.

You can use the Unload statement to remove any control created with Load . Howeve r,
Unload cannot be used to remove controls created at des ign time, whether they are part of a
control array or not.

Setting an Object's Coordinate System


If yo u' re sati sfi ed wi th the twip coordinate system used so far, you don ' t need to rese t any of
the coordinate system s used in Vi sual Basic graphics, and you can skip thi s sec ti o n for now .
But if yo u wa nt to use a d ifferent coo rdi nate sys te m , read o n.
Every graphical operation described in this chapter (including resizing, mov in g, a nd draw in g
lines and ci rcles) uses the coordinate system of the drawing area or container:
• Ali graphi cs and Print method s use the coordinate system of the object being w ritten to. ·
For example, statements th at draw inside a picture box control use th e coo rdin ate sys tem
of that picture box.
• When you move or resize a co ntrol , the relev ant coordinate system is that of the
container. If you draw the object directly on the form, the form is the conta in er. If you
draw the control o n top of a frame or picture box , the frame or picture box is the
co ntainer.
• Stateme nts th at res ize or move a form always use twips. The upper-left comer or the
screen is always (0 , 0) .
When you resize or move form s, you may want to chec k the Height and Width properti es
of the Screen obj ect to see how mu ch room there is on the monitor.

The terms "coordinate sys tem" and "scale" are interchan gea ble. You set the coordin ate
sys tem for a particul ar object (form or picture box control) by using the objec t's scale
properti es and by usin g the Scale method. You can set a scale in one of three d ifferent ways:
• Create a c usto m scale
• Select one of severa! standard scales
• Reset to the default scale

The nex t four sec ti om, cxpléiin l 1u v.. to se t c ustom, stand ard, and defa ult ~cale~ .

Microsoft Visual Basic Programmer's Guide


172 Part 3 Application-Building Techniques

Creating a Custom Scale


Every for m and picture box has severa! scale properties (ScaleLeft, ScaleTop, ScaleWidth ,
ScaleHeight, and ScaleMode) and one method , Scale, that yo u can use to set a scale
(coordinate sys tem). This section show s how lo use mo st of the scale properties. Unlike the
Scale method , you can use these properties ei th er to se t th e scale or lo get information .
You can use an obj ec t's ScaleLeft, ScaleTop, Scale Width , and ScaleHeigh t properties to
create a custom scale. The ScaleMode prope rt y spec ifi es one of severa! standard scales, and
is di sc ussed la ter in thi s chapter.
The ScaleLeft and ScaleTop properties spec ify w hat numeric value is ass igned to the upper-
left comer. For example, these statements set lh e va lu e of th e upper- left comer for the
current form:
Sca l eLeft = 100
ScaleTop = 100

These stateme nts se t the value of the upper-lefl comer for a pi cture box named
GraphicsArena:
Graph icsArena . ScaleLeft = 100
GraphicsArena.ScaleTop = 100

These stateme nts define the upper-left co rn eras (100, 100). A ltho ug h the stateme nts don ' t
direc tl y ca use any physical change, they alter the effec t of s ubseq uen t statements. For
exampl e, a s ubsequ en t statement th at sets a contro l" s Top property to 100 places th e object
at the ve ry top of its contain er.
The Sca leW idth and ScaleHeight properties define units in terms of the c urrent w idth and
height of the drawing area. For examp le:
ScaleWidth = 1000
ScaleHeight = 500

These statements define a hori zontal unit as 1/1 ,000 of th e curren t inte rn a] wid th of th e form
and a vert ical unit as l /500 of the current interna! he ig ht of th e form . 1f th e fo rm is la ter
res ized, th e units remain the same .

Note ScaleWidth and ScaleHeight define units in terms of th e inte rna] d imensio ns of the
object - th ese dime ns ions do not inc lu de the bordcr thickness . Thus , ScaleW idth and
ScaleHeight always refer to the amou nt of room uva il ab le inside th e object. The di st in cti on
between interna] and extern a! dimension s (specified by Wid lh and Heigh t) is particul arl y
important wi th fo rm s, w hi ch can have a thi ck bordcr. T he un its can a lso differ: Widlh and
He ight are always expressed in tem1s of the cu11wi11er 's coordin ate sys tem ; ScaleWidth and
ScaleHeight determ in e lhe coordin ate system or the objec t itse lf.

A li four of th ese scale properties can in c lud c rractions , and th ey a lso ca n be ncga ti ve
numbers. Nega ti ve sc ttings for the ScaleW id th and Sca le He ig ht propert ies change th c
orie ntation of th e coord in ate sys tem.

Microsoft Visu al Basic Programmer's Guide


Chapter 13 Creating Graphical Effects 173

The scale shown in Figure 13.6 has ScaleLeft, ScaleTop, ScaleWidth, and ScaleHeight ali
set to 100.

As X increases, position moves right.

11'
100,100
As Y ScaleLeft = 100
increases, Sea/e Top = 100
position ScaleWidth = 100
moves ScaleHeight = 100
down.

200,200
11

Figure 13.6 Scale running from (100,100) to (200,200)

Note that coordinates increase in value as yo u run from top to bottom, and from left to right.
If you want to change thi s scale so th at coordinates increase as you go from bottom to top,
then you set ScaleTop to 200 and ScaleHeight to - 100, as shown in Figure 13.7 .
As X increases, position moves right.

11' •
100, 200 200,200
As Y ScaleLeft = 100
in creases, Sea/e Top = 200
position ScaleWidth = 100
moves up. ScaleHeight = -100

100,100

Figure 13.7 Scale with negative ScaleHeight setting

Microsoft Visual Basic Programmer's Guide


174 Part 3 App lication-Building Techniques

The Scale Method: A Shortcut


You also can spec ify a custom scale by using thi s version of the Scale method. The
sy ntax is:
[object. ]Scale (xl, y ]) - (x2 , y2)

The values of xl and yl determine the settings of the ScaleLeft and ScaleTop properti es. Th e
differences be twee n the two x coordinates and the two y coordinates determine the setting
of ScaleWidth and ScaleHeight, respectively. For example, suppose you set the coordinate
system fo r a form by settin g end points (100,100) and (200,200):
Scale (100, 100) - (200, 200)

Thi s sta1emen1 defines th e fonn as 100 unit <; wicle and 100 units hi gh . With thi s scale in
place, the follow in g statement moves a control exactly o ne-fifth of the way across the form :
Mov er.Left = Mover.Lef t + 20

Specifying a valu e of x2 >xl , or y2 >yl , has the same effect as settin g ScaleWidth or
ScaleHeight to a negati ve va lu e.

Selecting a Standard Scale


Instead of defin ing units directly , yo u can define them in terms of a standard scale by settin g
the ScaleMode property to one of the values shown below.
ScaleMode setting Description
o User-defined . If you se t ScaleWi dth or ScaleHeight direct ly.
the ScaleMode property is set to O.
Tw ips. There are 1,440 twips to one inch. (This is th e
defa ult scale.)
2 Points. There are 72 points to one inch.
3 Pixels. A pi xel is the smallest unit of resolution on the
monitor.
4 Characters. A character is 1/6 of an inch high and 1/ 12 of an
inch wide.
s lnches.
6 Millime ter:-,.
7 Centimeters.

All of th e mode s above , except for O and 3, refer to printed le ngths. For example, an item
th at is two unils lo ng in the ce ntimeter system is two centimeters w hen printed.

Microsoft Visual Basic Programmer's Guide


Chapter 13 Creating Graphical Ettects 175

These statements set the ScaleMode property :


Sca leMod e = 5 ' Set sca le to inches for this form .
Picturel.ScaleMode = 3 ' Set scale to pixels far Picturel .

Setting a value for ScaleMode causes Visual Basic to redefine ScaleWidth and ScaleHeioht b
so that they are consistent with the new scale. Setting ScaleWidth or ScaleHeight directly
causes ScaleMode to be set to O.

Resetting to the Default Scale


If you want to reset the scale to the default -so that the upper-left comer has the coordinate
(0,0) and units are egua] to twips - use the Scale method with no arguments:
íobject.]Scale
For example, the following statement resets the scale for the form to which the code is
attached :
Sca le

For more information on setting coordinate systems:

m Search Help for:


coordinate systems

The Fundamentals of Drawing


The graphics methods in Visual Basic enable your application to draw points, lines, boxes,
circles, and other shapes. Certain fundamental concepts appl y to ali graphics methods.

Where Can Vou Draw?


Every graphics method draws output on a specified form or picture box . To indicate what
area you want to draw in, precede a graphics method by the name of sorne object (form or
picture box control) . If you omit the object, Visual Basic assumes the form to which the
code is attached. For example, the following statements draw a point on the form MyForm,
picture box Picture 1, and the current form :
MyForm.P Set (500, 50 0)
Pi ct urel . PSet (500. 50 0 )
PSe t ( 500, 500 l

As we ' ve seen in the previous section, "Setting an Object's Coordinate System," each
drawing area has its own coordinate system that determines what units mean. In addition ,
every drawing area has its own complete set of graphics properties.

Microsoft Visual Basic Programmer's Guide


176 Part 3 Application-Building Te chniques

Persistent Graphics
When a window is moved overa form, temporarily hiding it, and then is moved away again,
sorne of the contents may need to be redisplayed. If there are lines, circles, or text on the
form, you usually want them to reappear exactly as you placed them there. Thi s is what is
meant by persistent graphics.
You can make Visual Basic handle this detail automatically, but there is a cos t in memory.
Eac h form and picture box has an AutoRedraw property . AutoRedraw is a Boolean (i nteger)
property that when set to True (-1) causes graphics output to be saved in memory .
Yo u can use computer memory more efficiently by setting thi s property for forms and
picture box controls:
• When the AutoRedraw property of a resizable form is set to True, Visual Basic creates a
memory im age equal in size to the entire screen. Sav ing an image thi s large enables th e
application to retain graphics output even if it is drawn outside the current form size;
when the form is maximized, all the graphics output appears .
• When the AutoRedraw property of a picture box is set to True, Visual Basic creates a
memory image exactly the same size as the picture box. Graphics output drawn outside
the picture box never appears later, even if the size of the picture box changes.

If you want to conserve memory, create a picture box for all drawing effects and leave
AutoRedraw set to False (0) for the form .
Altematively, you can leave AutoRedraw set to False for the form and all its picture boxes,
and then manage graphics redrawing directly . You can include code that redraws ali lines,
cire les, and points as appropriate when the form or picture box recogni zes a Paint event
Thi s approach usually works best when you have a limited amount of graphi cs th at you can
reco nstruct easily.
A Pa int event procedure is called whenever part of a form or picture box needs to be
redrawn - fo r example, when a window temporarily covers the object and moves away , or
when resizi ng causes graphics to come back into view. If AutoRedraw is set to True, the
objec t' s Paint procedure is never called.
You can change the setting of AutoRedraw at run time. If AutoRedraw is False (0), graphics
and output from the Print method are written to the screen only, not to memory . If you clear
the object with the Cls method, any output written when AutoRedraw was set to True does
not get cleared. This output is retained in memory , and you must set AutoR edraw to True
aga in to clear it.

Microsoft Visual Basic Programmer's Guide


Chapter 13 Creating Graphical Ettects 177

Graphics Methods and Properties


T hi s chapter describes four graphics methods, summ ari zed below, which apply to form s and
picture boxes.
Method Description
Cls Clears all graphics and Print output.
Pset Sets an indi vidual pixel on.
Point Return s the color value of a specified point.
Line D raws a line, rectangle, or fill ed-in box.
Circle D raws a circle, ellipse, or are.

Each of these methods is described in thi s chapter.


The Print method also can be considered a graphi cs meth od, becau se its output is written to
the obj ect and is saved in the memory image (if AutoRedraw is on) just like the PSet, Line,
and Circle methods.
Forms and picture boxes have the fo llowing graphics properti es.
Category Properties
Current drawing location CurrentX, CurrentY
Drawing techniques DrawMode, D rawS tyle, DrawWidth
Filling tec hniques Fil!Color, Fill Style
Colors BackCo lor, ForeCo lor

In addition, each form and picture box has ali of the scale pro perti es described earli er, in the
section "Setting an Object' s Coordinate System ," and the fo nt properti es desc ribed in
Chapter 12, "Displaying and Printing Informati on."
You' ll see how to use most of these properties later in thi s chapter. But there are two
properti es yo u' ll probably want to use ri ght away: BackCo lor and ForeColor. BackC olor
paints the background of the drawin g area. If BackColor is li ght blue, then the en tire area is
light blue when you clear it. ForeColor (foreground) determines the color of tex t and
graphi cs drawn on an object, alth ough sorne graphics meth ods give yo u the option of
specify ing a different foreground color.
The nex t secti on shows you how to select a color at run ti me. For info rmati on on addin g
color to your application s at design time:

111
Search Help for:
Color palette a See Tutorial Lesson:
" Creating Custom Applications "

Microso ft Visua l Basic Programmer's Guide


178 Part 3 Ap pl ication -Building Techn iques

The World of Color


Vi sual B as ic uses a consistent sys tem fo r all color properti es and graphi cs methods. A color
is represented by a long integer, and this value has the sam e meaning in all contexts that
specify a color.
There are four ways to spec ify a color value at run time:
• Use a prev iously defined constant, suc h as one of the values in CONSTANT.T XT.
• Use the RGB fun ction .
• Choose a QuickBasic color with th e QB Color fun cti on.
• Enter a color value direc tl y.

Using a Previously Defin ed Constant


You don' t need to understand how color values are generated if you use the constants fro m
the fil e C ONSTANT.TXT. Just copy these defi nitions into the global module. For exampl e,
the foll owin g statement defines the sy mbo lic constant RED :
Gl obal Co nst RED= &HFF&

With this definition in your global modu le, yo u can use the symbolic name RED wh enever
you want to specify red as a color arg um e nt or co lor property setting. For example:
BackCo l or - RED

T he CONSTANT.TXT fil e also pro vides co nstants for Windows default system co lors.
T hese va lues do not set specific co lors. but te ll Vi sual Basic to use one of the colors that th e
user c hooses in the Control Panel. sing such numbers ca uses your application to appear
di fferently on eac h user' s system, but the advan tage is th at the applicati on can be made to
look more consistent with other Windows app licati ons fo r any given user.
For more informati on on the CO STA T.TXT file:

Search Help for:


111 CONSTANT.TXT

Microsoft Visua l Basic Programmer's Guide


Chapter 13 Creating Graphical Effects 179

Using the RGB Function


You can use the RGB function to specify any color.

To use the RGB function to specify a color:


1 Assign each of the three primary colors (red, green, and blue) a number from O to 255, O
denotin g the least intensity and 255 the most.
2 Give these three numbers as input to the RGB function, using the order Red-Green-Blue.
3 Assign the result to the color property or color argument.

Every visible color can be produced by combining one or more of the three primary colors.
For example:
Forml.BackColor = RGB(0 , 128. 0) Use medium green.
Form2.BackColor = RGB(255, 255, 0) ' Use yellow (red+ green).
PSet (100, 100), RGB(0, 0, 64) ' Set point to dark blue.

For more information on the RGB function, see the Language Reference, or:

m Search Help for:


RGB a See Tutorial Lesson:
"Creating Custom Applications"

Choosing a OuickBasic Color with the OBColor function


If you ' re portin g code from QuickBasic, or if you're accustomed to QuickBasic color values,
you can use them by calling the QBColor function. This function takes a single number that
specifi es a QuickBasic color number from O to 15 , and returns a long integer that can be
used in any Visual Basic color argument or color property setting. For example:
Forml .BackCo lor = QBColor (5)

For more information on the QBColor function, see the Language Reference, or:

m Search Help for:


OBColor

Microsoft Visual Basic Programm er's Guide


180 Part 3 App li cati on-Buli di ng Techn1 ques

Entera Color Setting Directly


You can ass ign numbers to color properties (and arguments) directly, if you understand how
colors arMepresented in Visual Basic. In most cases, it 's much easier to enter these numbers
in hexadecimal.
Each color setting (property or argument) is a four-byte integer using the three least-
significant bytes to represen! red, green, and blue, as shown in Figure 13.8.

Blue Green Red


0-255 0-255 0-255

(ar &HBO far system


default color)

Most-significant byte Least-significant byte

Figure 13.8 Byte layout of co lor values

Consequently, you can specify a color as a hexadecimal number using this syntax :
&HBBGGRR

The BB specifies amount of blue, GG amount of gree n, and RR amo unt of red. Each of these
fragme nts is a two-dig it hexadecimal number fro m 00 to FF. The median value is 80. Thu s.
the fo ll owing nurnber spec ifies gray, which has the median amount of all three colors:
&H808080

Settin g the rnost signifi cant bit to 1 changes the meaning of the color value: It no longer
represents an RGB color, but an environrnent-wide color specified through the Control
Panel. The values that correspond to these system-wi de colors range from &H80000000 to
&H 8000001 2 and are included in the CONSTANT.TXT file .

Clearing the Drawing Area


Any time you wa nt to clear a drawin g area and start over, use the Cls method . The specil'iecl
drawin g area is repainted in the background color (BackColor). The Cls method has the
simpl est sy ntax or any of the graphics methods:
f o/Jje('f JCls

Using the Cls methocl witho ut a specified object clears the form to whi ch the code is
at tac hed.

Microsoft Visual Basic Programmer's Guide


Chapter 13 Creating Graphical Effects 181

Plotting Points
Another simple graphics operation is controlling an individual pixel. The PSet method sets
the color of a pixel at a specified point :
[object .] PSet (x , y)[, color]

The arguments x and y are single precision, so they can take either integer or fractional
input. The input can be any numeric expression, including variables.
If you don ' t include the color argument, PSet sets a pixel to the foreground color
(ForeColor). For example, the following statements set various points on the current form
(the form to which the code is attached), MyForm, and Picturel:
PSet (300. 100)
PSet (10.75, 50.33)
MyForm.PSet (230. 1000)
Picturel.PSet (1.5, 3.2)

Adding a color argument gives you more control :


PSet (50, 75). RGB (0, 0, 255) · Se t 50,75 to bright blue .

To "erase" a point, set it to the background color:


PSet (50, 75). BackColor

As desc ribed in the section "The Step Keyword" later in thi s chapter, you can precede the
(x, y) coordinates by Step, which makes the point relative to the last location drawn .
Closely related to the PSet method is the Point method, which return s the color value ata
particular location :
PointColor = Point (500, 500 )

For more information on the PSet method, see the Language Reference, or:

m Search Help for:


PSet

Micro so ft Visual Basic Programmer's Guide


182 Part 3 Application-Building Techniques

Drawing Lines and Shapes


Although clearing the drawing area and plotting individual points can be useful, the most
interesting graphi cs methods draw complete lines and shapes.

Drawing Lines
To draw a line between two coordinates, use the simple form of the Line method, which has
this sy ntax :
[object .]Line [(xl , y l)] - [x2, y2 ) [, color]

The brackets indicate that objecr is optional ; if omitted, the method draws to the form to
which the code is attac hed (the current forrn) . The first pair of coordinates also is optional.
As with all values given for coordinares, the arguments x and y can be either integer or
fractional numbers. Visual Basic draws a line that ~_n cludes both end points.
For example, this statement draw s a slanted line on a form. The results are shown in Figure
13.9.
Line (500, 500) - (2 000 , 2000 )

1m lineDemo aa

Figure 13.9 A line drawn with the Line method

The first pair of coordinares (xl , _v l) is optional. If you omit this end point, Visual Basic uses
the object's c urrent x, y location (drawing coordinates) as the end point. The current location
can be specified with the CurrentX and CurrentY properties, but otherwise is equal to the
last point drawn by a previous graphics or Print method. If you haven' t previously used a
graphics or Print rnethod or se t CurrentX and CurrentY, the current location is the object 's
upper-left comer by default.

Microsoft Visual Basic Programmer's Guide


Chapter 13 Creating Graphical Ettects 183

For example, the following statements draw a polygon by connecting five points :
CurrentX - 600
CurrentY - 600
Line - (10 00, 500)
Line - (1200, 800)
Line - (800, 1100)
Line - (500, 1000)
Line (600, 600)

You can start experimenting with graphics by opening a blank form and placing statements
in a Form_Load or Form_Click procedure. For example:
Sub Form_Click ()
Line (500, 500) - (2000, 1200)
End Sub

By adding variables and loops , you can create interesting pattems. For example, the
following procedure quickly creates a spoked pattem on the screen. The results are shown in
Figure 13.1 O.
Sub Form_Click ()
Dim I As Integer
For I = 1000 To 2000 Step 50
Line (500, 500) - (2000. 1)
Next
End Sub

al lineDemo aa

Figure 13.10 A spoked pattern

This variatio n creates a relatively so lid pattem , and the drawing is slower:
Sub Form_Click ()
Dim l As Integer
For I - 1000 to 2000
Line (5 00, 500) - (2000, 1)
Next I
End Sub

Microsoft Visual Basic Programmer's Guide


184 Part 3 Application-Bui ldin g Techniqu es

Varying Lines with DrawWidth and DrawStyle


So far , yo u' ve drawn relati vely standard lines, usin g a sma ll wi dth , so lid patte rn , and
fo regro und co lor. This secti on shows how to vary those qualiti es .
To vary the co lor of the line , use the optional color argument. For exampl e, thi s statement
draws a clark blue line:
Line (500 , 500) - ( 2000 , 200 0 ) , RGB (0, 0, 255)

Y ou also can change the color of th e line by first setting the ForeColor property fo r th e
obj ect where the line is being drawn.
T he three pro perti es th at affec t how lines are drawn are DrawWidth , DrawS ty le , and
DrawMocle. T he DrawWidth property specifies the width of the line in pi xels, and affects
the PSet ancl Circle methods as well as th e Line method . For exam ple . th e fo ll ow in g
procedurc uses Dra wWid th to cl raw lines of se vera! d iffe rent wid th s. T he res ulb are show n
in F ig ure 13.11.
Sub Fo r m_Clic k ()
Dr awW idth = 1
Li ne (10 0 , 1000 ) - (3 000, 1000)
Dr awWid th = 5
Li ne (1 00, 1500) - (3 000 , 1500)
Dr awWi dt h = 8
Li ne ( 100, 2000) - (3 000 , 2000 )
End Sub

mi DrawWidth Demo aa

Figure 13.11 Lines of varying width

Microsoft Visual Basic Prog rammer's Guide


Chapter 13 Creating Graphical Ettects 185

T he DrawStyle property specifies whether the line is salid or has a broken pattern . This
pro perty is an integer whose settings represent the fo llowing.
Setting Description
O Salid (the default)
1 Series of dashes
2 Series of dots
3 Repeated dash-dot pattern
4 Repeated dash-dot-dot pattern
s Transparent (drawing has no effect)
6 Inside salid (see below)

T he inside salid style (DrawStyle = 6) is the same as salid, except when you are using a
wide line to draw a box. In thi s case, the solid style draws th e line half inside, ha lf outside
the box. The inside solid style draws the line entirely inside the box . See the section
"Drawing Boxes" later in this chapter to see how to draw a box.
The following procedure demonstrates a11 of the supported settin gs of the DrawSty le
property by creating a loop in which the setting goes from O to 6, one step at a time. The
results are shown in Figure 13. 12.
Sub Form_Click ()
Dim I As Intege r , Y As Long
For I = 0 To 6
DrawSty l e = I
Y= (2 00 * !) + 1000
Li ne (2 00, Y) - (2400, Y)
Ne xt I
End Sub

11 DrawStyle Demo DII

Figure 13.12 Lines drawn with different settings of the DrawStyle property

Microsoft Visual Basic Programmer's Guide


186 Part 3 Application-Building Technique s

Using the DrawMode Property


The DrawMode property determines what happens when yo u draw one pattem on top of
another. Although changing the DrawMode property usually has sorne effect (especially
with color systems), it is often not necessary to use this property when you are drawing on a
blank or pure white background, or on a background of undifferenti ated color.
Ym, can set DrawMode to a value from I to 16. Commonly used settings are listed below .
Setting Name of setting Description
4 Not Copy Pen Draws the inverse of the line
pattem, regardless of what is
already there.
7 Xor Pen Displays difference between
line pattern and th e ex istin g
di splay, as explained later in
this section. Drawing an
object twice with this mode
restores the background
precisely as it was .
11 Nop No operation. In effect, this
tums drawing off.
13 Copy Pen (defa ult) Applies the line 's pattem ,
regardless of what is already
there.

Other se tti ngs are used only rarely. For mo re informatio n on th e DrawMode property , see
the Language Reference, or:

Search Help for:


111 DrawMode

A DrawMode setting of 7 is useful fo r anim ation . Draw ing a line twice restares the exis ting
display precisely as it was befare the line was drawn. This makes it possible to create one
object that " moves over" a background without corru pting it, beca use you can restare the
background as you go. Most modes are not guaran teed to preserve the old background .
For exampl e, the following code moves a circle every time th e mouse is clicked. No matter
what pattern was underneath the ci rcle, it gets restored.
Sub Form_Click ()
ForeColor = 255: DrawMode = 7
Ci rcl e ( CurrentX. CurrentY). 1000
CurrentX = CurrentX + 220
CurrentY = CurrentY + 220
Circle (CurrentX. CurrentY). 1000
End Sub

Microsoft Visual Basic Programmer's Guide


Chapter 13 Creating Graphical Effects 187

The Xor Pen draw mode, and most of the other DrawMode settings, work by comparing
each individual pixel in the draw pattem (called the "Pen") and the corresponding pixel in
the existing area (called the "Destination"). On monochrome systems, the pixel is either
tumed on or off, and Visual Basic performs a simple logical comparison: It tums a pixel on
if either the Pen or Destination pixel is on, but not both.
In color systems, each pixel is assigned a color value. For DrawMode settings such as Xor
Pen, Visual Basic compares each corresponding pair of pixels in the Pen and Destination ,
and perforrns a binary (bit-wise) comparison. The result determines the color value of the
resulting pixel , as shown in Figure 13 .13 .

"Pen"- " Destination"-


A pixel in the A pixel in the
draw pattern ex i~ting display

1111 0011

Xor operation

'
Resulting
pixel

1100

Figure 13.13 Comparing the color value

The Step Keyword


Several graphics methods (PSet, Line, and Circle) specify one or more points using this
syntax :
(x , y)

Each of these points can be preceded by the Step keyword , which specifies that the point is
relative to the last point drawn. Visual Basic adds the values x and y to the values of the last
point drawn. and the sums determine the new point. For exa mple, the statement
Line (100, 200) - (150, 250)

is equivalent to
Line (100, 200) -S tep (50, 50)

Microsoft Visual Basic Programmer's Guide


188 Part 3 Applic atio n-Building Techniques

In many situations, the Step keyword saves you from having to constantly keep track of the
last point drawn . Often you are more interested in the relative position of two points rather
than their absolute position .

Drawing Boxes
You can draw a box by using features of the Line method presented so far in thi s chapter.
The following example draws a box with upper-left comer at (500, 500) and measurin g
1.000 twips on each side:
Line (500, 500) -Step (1 000, 0)
Line Step (0, 1000)
Line - Step (-1000. 0)
Line - Step (0, - 1000 )

However. Visual Basic provides a much simpler way to draw a box . When you use the B
option wi th the Line method (B comes after the argument color), Visual Basic draw s a
rec tang le, treatin g the specified points as opposite corners of the rectangle . Thus , yo u could
replace the four stateme nts of the previous example with:
Line (500 , 500) -S tep (1000, 1000), . B

Note that two commas are required before B, to indicate that the color argument was
s kipped. (Oth erw ise, B could be interpreted as a variable giving the color value) .
As long as you do not cha nge the settin g of the FillStyle property, the box appears empty .
Actual ly. the box does get filled usi ng the current FillStyle and FillColor settings. But
Fill Sty le defaults to l (Transparent), which specifies an invisible pattern. You ca n chan ge
th e FillStyle property to any of the settin gs li sted below.
Setting Description
o Solid. Fills in box with the color set for the Fil!Color
property.
Transparent (the default). Graphical object appears e mpt y.
no matter what color is used.
2 Horizontal lines.
..,
.) Vertical lines .
'-+ Upward diagonal lines.
s Downward di agonal lines.
6 Crosshatch .
7 Diagonal crosshatch.

Thu s, se ttin g Fil!Style to O fills th e box so lidly with the color set for the Fil!Color propert y.

Microsoft Visual Basic Programmer's Guide


Chapter 13 Creating Graphical Ettects 189

Another way to fill the box is to append an F to the B. (Note that F cannot be used without
B.) The following statement fills the box with a solid pattern, using the same co lor used to
draw the line (specified by the DrawColor property) . The result is shown in Figure 13.14.
Line (50 0, 500) -S tep (1000, 1000) , , BF

11 FillDemo ªª

Figure 13.14 Filling a box with a sal id pattern

Drawing Circles
The Circle method draws a variety of circu lar and elliptical (oval) shapes. In add ition ,
Circle draws ares (segments of circles) and pie-s haped wedges. You can produce many
kinds of curved lines by using variations of Circle.
To draw a perfect circle (as opposed toan ellipse), Visual Basic needs only th e location of a
c ircle' s center and the length of its radiu s. The syntax for a perfect circle is:
[object .]Circle [Step] (x, y), radius [, color]

The bracke ts indicate that both object and the Step keyword are optional. lf object is
om itted, the c urrent form is assumed. The arguments x and y are the coordinates of the
ce nte r, and radius is the radius of the circle. For example, this state ment draws a circle with
a ce nter at ( 1200, 1000) and radius of 750:
Circle (1200, 1000), 750

The exact effec t of thi s statement depends on the coordinate sys tem in use and the size of the
form. Because the size of the form is unknown , yo u don ' t even know if the circle wil l be
visible. Using the drawing area's ScaleWidth and ScaleHeight properties solves thi s
problem. For example, this statement ensures that the center of the circle is at the cen ter of
the form:
Circ le (Scale Width/2, Sca leHeigh t/2), ScaleWidth/4

By usin g the Step keyword , you can make the location of the circ le relative to the center of
the form , in stead of relative to the upper-left comer:
CurrentX = Sc aleWidth/2
CurrentY = ScaleHeight/2
Circle Step (200, -3 00), 1000

Microsoft Visual Basic Programmer's Guide


190 Part 3 Application- Building Techniques

Note The radius of the circle is always specified in term s of hori zontal units . If your
coordinate system uses the same hori zontal and vertical units (which it does by default), you
can ignore thi s fact. However, if you use a custom scale, hori zontal and vertical units may
corres pond to different di stances. In the exa mples above, the radiu s is specified in hori zontal
units, and the actual height of the circle is guaranteed to be equal to its actual width .

Drawing Ellipses
The aspect ratio of a circle controls whether or not it appears perfectly round (a perfect
circ le) or elongated asan ellipse. The compl ete sy ntax for the Circle method is:
[objec1. ]Circle [Step] (x, y ), radius , [color] , [start], [ene/] , aspect

Here. mpecl is a positi , ·e fl oati ng-point number. Thi s mean s yo u can specify in teger or
fractional ex pressions, but not negati ve values.
The arg ume nts start and end are used in displaying ares, as described in the next sec tion .
These arguments are optional , but the commas are necessary if you want to skip arg um ents.
For example, if you include the radius and aspect arguments, but no color, start, or end
argument, yo u must add four successive commas to indicate that you ' re skipping the three
arg uments:
Cir cle (1 000, 1000) , 500,.,. 2

T he argument aspect specifies the ratio of the verti cal to hori zo ntal dimensions. Large
vaJu es fo r aspect produce ellipses stretched o ut alo ng th e ve rti cal axis , while small valu es
for aspect produce ellipses stretched out along the hori zo ntal axis. Since an ellipse has tw o
rad ii - one hori zontal x-radius and one ve rti cal y- radius - Yi suaJ Basic uses th e s in g le
arg um e nt radius in a Circle statern ent as follows : If aspee! is less th an one, radius is the x-
radiu s; if aspect is greater than or equ al to one, radius is the y-radiu s.

Note The arg ume nt aspecr always specifies the ratio between the vertical and hori zontal
dim e nsions in term s of true ph ys ical di sta nce. To ensure th at this happens (even when yo u
use a c usto m scale), th e radiu s is specified in terms of hori zontal units. See the end of th e
previous sec ti on for more information .

Microsoft Visual Basic Pro gra mmer's Guide


Chapter 13 Creating Graphical Ettects 191

Exa mple The following procedure illustrates how different aspect values determine whether Circle
uses the argument radius as the x-radius or the y-radius of an ellipse. The output is shown in
Figure 13.15.
Sub Form_Click ()
FillStyle = 0 ' Draw solid ellipse .
Circle (600, 1000), 800, ... 3
FillStyle = 1 ' Oraw empty ellipse.
Circle (1800, 1000), 800 .... 1/3
End Sub

ID Ellipses Demo aa

Figure 13.15 Ellipses drawn with the Circle method

Drawing Ares
An are is a segment of an ell ipse ora circle; think of an are as a curved line. To understand
how the Circle method draws ares , you need to know how Vis ual Basic measures ang les .
Visual Basic uses the radian as its unit of angle measure, not only in the Circle method , but
also in the trigonometric functions such as Cos, Sin, or Tan.
The radian is closely related to the radius of a circle. In fact , the word " radian" is deri ved
from the word "radius." The circumference of a circle equals 2 * Pi * radius , w here Pi is
equ al to approximately 3. I 41 S926S. Similarly, the number of radians in one com plete angle
of revolution (or 360 degrees) eq ual s 2 * Pi, ora littl e more than 6.28 .
T hi s statement calcul ates Pi to double precision :
Oim Pi As Oouble
Pi = 4 * Atn(l)

Microsoft Visual Basic Programmer's Guide


192 Part 3 Application -Building Technique s

lf you think of angles in term s of degrees, here are sorne common equivalents.
Angle in degrees Angle in radians
360 2*Pi (approximately 6.283)
180 Pi (approximately 3. 142)
90 Pi/2 (approximately 1.571)
60 Pi/3 (approximately 1.047)
45 Pi/4 (approximately 0.786)

If you picture a clock face on the sc ree n, Circle measures angles by starting at the three
o' clock position and rotating counterc lockw ise , as shown in Figure 13. 16.

90 degrees
(TI/2 radians)

- - - - - 3rr./2 radia ns
_ __,,__ _ _ TI radians
- - - -- - - - - rr./2 radians
·..-_ __,_ _ _,___ _,____ 7 radian
180 degrees Odegrees
(TI radians) (O radians)

270 degrees
(Jrr./2 radians)

Figure 13.16 How ang les are measured far a circ le

The general formu la for convertin g from degrees to radians is to multiply degrees by Pi/180 .

Microsoft Visual Basic Programmer's Guide


Chapter 13 Creating Graphical Effects 193

To draw an are, give angle arguments defi ning the are 's limits. The sy ntax is:
area .Circle Step(x, y ), radius, color, start, end, aspect

In th e fo llowing example, the Circle method is used to draw seven ares. The innermost are
starts at the three o'eloek position (O radians) and the outermost are starts at the six o'eloek
position (3/2 * Pi). The results are shown in Figure 13.17.
Sub Form_Click ()
Height = 550 0
Const PI= 3.14159265
StartAngle = 0
For Radius% = 1000 To 2200 Step 200
EndAngle = (EndA ngle + (PI / 2)) Mod (2 * PI)
Circle (25 00, 2500) , Radius%, Start Angle, EndAngl e
StartAngle = StartAngle + (PI / 4)
Next Radiu s%
End Sub

11 Ares Demo aa

Figure 13.17 Using the Circle method to draw ares

If th e arg um ent start or end is negati ve, Visual Basie draws a line eonneeting the eenter of
th e eire le to the negative end point. For exampl e, the following procedure draw s a pie with a
sli ce re moved , as shown in Figure 13.8 on the nex t page.
Su b Form_Click ()
Const PI= 3.14159265
Circle (35 00, 1500), 1000 , . -PI/ 2,- PI / 3
End Sub

Microsoft Visual Basic Programmer's Guide


194 Part 3 Ap plication-Building Techn iques

Both the srarr and end arguments are negative, so lines are drawn co nn ecting both end points
of the are to the center of th e c ircle.

IZI Pie-Shape Demo aa

Figure 13.18 Using negative arguments to con nect an are to its center

Note that the are is drawn the long way between the two angles rather than the short way.
T hi s is because Visual Basic alw ays draws ares in a counterclockwise (positive) direction. lf
the angles are given in the reverse order (Pi/3, Pi/2), Visual Basic draws the are usin g the
short di stance between the two angles, as shown in Figure 13 .19.

IZI Pie-Shape Demo aa

V
Figure 13.19 Ettect of reversing arguments

This example on the prev ious page also illustrates that - Pi/2 and - Pi/3 indicate th e same
angles (po ints on the c ircle) th at Pi/2 and Pi/3 do. The onl y signifi cance of the nega ti ve sig n
is that it ca uses Vi sual Basic to draw a line between the point and the center of the ci rc le.

Microsoft Visual Basic Programmer's Guide


Responding to Mouse Events

As you ' ve seen in earlier chapters, Click is a simple mou se event. It ' s adequate for situat ions
where you respond the same way to any mouse click on an object.
Your applications also can respond to other mou se events - such as MouseDown and
MouseUp . Forms and picture boxes can detect the exact position of the mouse pointer,
whether or nota button is being pressed. In addition , your code can respond differently to
left and ri ght mouse buttons and to combinations of buttons with the SHIFr, CTRL, or ALT
keys .
Close ly related to the mou se events are the drag-and-drop features in Visual Basic. These
include properties and events, and a Drag method that you can use to enable dragging
ope ration s at run time. The drag-and-drop feature s are especiall y versati le; yo u can support
dragging between forms , and you can support drag operati n or users without a mouse.
The main section s in this chapter are:
• Mouse Events
• Positioning a Control with the Mouse
• Graphi cal Mo s-:e,..~ - - - -~ ......~-~.....,;-'"'""""-....,-'""

• Dragg ing and


196 Part 3 Application -Build ing Techniques

Mouse Events
Forros and several types of controls recognize three mouse events (aside from drag events,
which are introduced later). You can use the following to respond to the exact location and
state of the mouse .
Event Description
MouseDown Recognized when the user presses any mouse button.
MouseUp Recognized when the user releases any mou se button .
MouseMove Recogni zed each time the mou se pointer is moved to a new
point on the screen.

The obj ec ts th at ca n recog nize th ese eve nt s inc lude form s, pi cture boxes. labels. and any
type of control that involves a list: list boxes, combo boxes, file list boxes, drive list boxes,
and directory list boxes .
A forro can recogni ze a mouse event when the pointer is overa blank portian of the forro . A
control can recogni ze a mouse event when the pointer is over the control.
When the use r presses and hold s down a mou se button , the same form or con trol continues
to recognize ali mouse events until the user releases the button . This is true even when the
pointer is moved off the obj ec t.
Ali three mou se eve nts use the same arguments.
Argument Oescription
Button A bit-fi eld argum ent in which the three leas t-significant bits
give the statu s of the mou se buttons.
Shift A bit-fi eld argument in which the three leas t- significant bits
give the statu s of the SHI FT, CTRL, and ALT keys .
X, y Location of th e mouse pointer, using the coordin ate sys tem
of th e object that rece ives the mou se event.

A bit-field argwn ent retums informati on in indi vidual bits, so that each bit indicates whether
a certain condition is on or off. Techniques for programming with these arg um ents are
desc ribed later. in th e sec tion "The Button and Shift Arguments ."

Microsoft Visual Basic Programmer's Guide


Chapter 14 Responding to Mouse Events 197

Positioning a Control with the Mouse


Yo u' ll find that you use the MouseDown event most often and that X and Y are the most
useful arguments. This section introduces MouseDown and the arguments X and Y.
The application shown in Figure 14.1 uses only a form and a picture box control. When the
user clicks a blank portion of the form, the picture box moves to that location .

1m Forml ªª

Figure 14.1 Moving a control to the location of the moJ,Jse pointer

The picture box has the default name Picturel. If you want to load an image into the picture
box , set its Picture property by using the Properties bar, as described in Chapter 13,
"Creating Graphical Effects."
A single procedure, Forrn_MouseDown, does all the work of this application :
Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single,
• Y As Single)
Picturel.Move X, Y
End Sub

That 's al i there is to it! The procedure uses the Move method to move the picture box
co ntrol to the location of the mouse (indicated by the arguments X and Y). This procedure
places the top left comer of the picture at the mouse location.
A revised version places the center of the picture at the mouse location :
Sub Form_MouseDown (Button As Integ e r, Shift As Integer, X As Single,
• Y As Si ngle)
Picturel.Move CX - Picturel . Wid th / 2), (Y - Picturel . Height / 2)
End Sub

For more information on the Move method, see the Language Reference, or:

Search Help for:


111 Move

Microsoft Visual Basic Programmer's Guide


198 Part 3 Ap plicatio n-Building Techn iques

Graphical Mouse Applications


This secti on shows how to use all th ree events - MouseMove, MouseU p, MouseDown -
and how to combine them with the graphi cs methods introduced in C hapter 13 , "Creating
G raphical Effects. " By combining mouse eve nts with these methods, you can create any
number of custorni zed drawing or paint applicati ons.

The Click-A-Line Application


The Cli ck-A-Line applicati on works in response to a mouse click by drawing a line from the
last draw ing locati on to the new position of the mouse. Thi s application uses the Line
method discus ed in Chapter 13. You ' 11 recall th at the fo ll owing sy ntax of the Line rnethod
draws fro m the last poin t drawn to the poi nt (x2 , y2):
Line - (r.?. , .? )

Click-A-Line uses a blank for m with one procedure, Form_MouseDow n:


Sub Form_ Mou seDo wn ( Button As Integer, Sh i f t As In tege r , X As Single,
• Y As Sing le)
Lin e - (X, Y)
End Sub

T he first line draw n starts at the ori gin (upper-left com er), whi ch is the default draw ing
locati on . T herea fter, the applica tion draw s a straight line frorn the last location drawn each
time the use r presses the mouse button dow n. The result is a seri es of co nnected lines, as
show n in Figure 14. 2.

Figure 14.2 Th e Cli ck- A-Lin e application draws line s w it h th e Line method .

Microsoft Visua l Basic Programmer 's Guide


Chapter 14 Responding to Mous e Events 199

The Scribble Application


Graphi cs methods can have very different effects when used in a MouseMove procedure
instead of a Mo use Down proced ure. For example, when placed in Form_MouseMove, the
simple Line method in the previous section produces a Scribble application that traces
move ment on a bl ank fo rm.
The Mou seMove event is recognized whenever the location of the pointer changes . The
followin g code draws a line between the current location and the previous location . As a
res ult, the app li ca ti on draws a co ntinuous, curved line corresponding to mouse movement.
as shown in Figure 14.3. Like the MouseDown procedure, the line created by the
MouseMo ve procedure starts at the default drawing location (the upper-left co m er).
Sub Form_MouseMove (Butto n As In te ger, Shift As Integer , X As Si ngle,
• Y As Single)
Li ne - ( X. Y)
End Sub

Scribble ªª

Figure 14.3 The Scribble Appl ic ation

How MouseMove Works


How man y times doe s the Mou seMove event get caJ!ed as the user moves the pointer across
the screen? Or, to put it anoth er way, if you move the pointer from the top of the sc ree n to
the bottom , how man y locations are involved?

Microsoft Visu al Basic Programmer's Guide


200 Part 3 Appl ica t ion -Building Techniques

Visual Basic does no t necessaril y generate a MouseMove event for every pi xel the mou se
moves ove r. The operating environment generates a limited number of mou se messages per
second. To see how often MouseMove events are actually recogni zed, you can enhanc e the
Scribble application with the following codeso that it draw s a small circle at each locatio n
wh ere a MouseMove event is recognized. The results are shown in Figure 14.4.
Sub Form_ Mou se Move (B utto n As Integer, Shift As Integer. X As Single,
• Y As Single)
Li ne - (X, Y)
Circle (X, Yl. 50
End Sub

Figure 14.4 A dem onstration of where MouseMove events occur

No te that the fa ster the user moves the pointer, the fewe r M o useMove events are recog ni zed
be twee n any two points. Man y c ircles clase together indicate th at th e user moved th e mou se
slow ly.
W hat's important to understand about MouseMove events is th at your appli cation can
recognize man y of them in quic k successio n. Therefo re , a MouseMov e eve nt procedure
sho uld no t do anything that req uires large amount s of computing time.

Using AII the Events Together


The Scribble ap plication is more useful if it enables the user to draw only while the mo use
button is he ld down , and then to stop drawin g when the button is re leased . This more
sop hi st icated version has to respond to three kind s of ac ti o ns:
• The use r presses the mou se button.
• T he user releases the mou se button .
• The user moves the poi nter.

Microsoft Visu al Basic Programmer's Guide


Chapter 14 Responding to Mouse Events 201

These acti ons correspo nd to the MouseDown, MouseUp, and MouseMove events. Each of
the three event procedures has a specifi c role. MouseDown and MouseUp in effect say,
"Tum draw ing on," or "Turn drawing off." In Visual Basic , yo u communicate such
information by creating a forrn-level variable to represent the drawing state. Type thi s
statement in the Declarations sec tion of form code:
Dim DrawN ow As Integer

We'II use DrawNow to represent two values: A value of False (0) will mean "Do not draw ,"
and a val ue of True (- 1) wi ll mean "Draw a line."
Variables are initiali zed to zero by default, so the application starts wi th drawing off.
Drawing is then turned on and off again by the MouseDown and MouseUp procedures:
Sub Form_MouseDown (Button As Integer, Shift As Integer. X As Single,
- Y As Sing l e)
DrawNow = - 1
Curr entX X
CurrentY - Y
End Sub

Sub Form_MouseUp (Button As Integer, Shift As Integer. X As Single.


• Y As Singl e)
DrawN ow = 0
End Sub

The first indented line in each procedure turn s drawin g on or off by se ttin g th e va lue of th e
form-level variab le DrawNow. ( DrawNow does not by itse lf have special meanin g, but it is
used by the MouseMove procedure.)
The MouseMove procedure draws a line only if DrawNow is T ru e (- J). O th erwise, it takes no
ac tion:
Sub Form_MouseMove (Button As Integer. Shift As lnteger. X As Single .
• Y As Single)
If DrawNow Then Line - CX. Y)
End Sub

This version of the Scribble application demon strates th e relati onship of events: When th e
user presses a mouse button, the MouseDown proced ure is ca lled just once. The
MouseDown event procedure signals to tum drawing on. Thereafter, MouseMove is invoked
many times as the pointer is dragged across the sc ree n.
No te th at the use of the Line me th od above omits the first endpoint, causing Vi sual Basic to
start drawing at the current drawing coordinates. By default , th e drawing coordinates
correspond to the last point drawn , but you can reset them by ass ignin g values to CurrentX
and CurrentY. In thi s appli cation, the MouseDown procedure sets CurrentX and Curren tY to
start drawing from a new location - the place w here the use r presses th e mouse button:
CurrentX X
CurrentY - Y

Microsoft Visual Basic Programmer's Guide


202 Part 3 Applicati on -Build ing Tec hniqu es

The Button and Shift Arguments


As your applications become more powerful , you may want to give users additional options
when using the mouse. You can wri te code th at responds differently to mouse events
depending on which button is used, or whether the SHIFf, CTRL, or ALT key is pressed. You
can provide these options by using the arguments Button and Shift with MouseDown,
MouseUp, anél M ouseMove procedures.

The Button Argument


The Button argument is an integer th at represents the state of the mouse. As mentioned
earli er in this chapter, it is a bit-fi eld argument - a value in which each bit represents a state
or condi ti on. The three least-significant (lowes t) bits represent the left, right, and middle
mouse buttons , as shown in Figure 14.5 .

left button
righ t button
middle button

O O M R L

lunused

Most-significant bits Least-significant bits


Figure 14.5 How bits represent the state of the mouse

The exac t meaning of these bits changes depe ndin g on the event, whi ch is why the
informat ion returned for the MouseMove event differs from that for the MouseDow n and
MouseUp events .
Yo u do n' t need to understand everythin g about how bits are set in order to use Button, but it
can help yo u dev ise more powerfu l uses for the argument, as you' ll see in the nex t sec ti ons.

Using Button with MouseDown and MouseUp


You use Button with MouseDown to determine whi ch button is pressed, and with MouseUp
to determine which button is released. For both events, you can test only whi ch button was
used; you cann ot test fo r whether two or more bu ttons are used at the same time.

Note In contrast, you can use the Mo useMove event to tes t not onl y for whi ch button is
pressed during the move, but also whether two or more buttons are pressed simultaneously.
You also can use MouseMove to test fo r whether only one button is pressed, which you
cann ot do with Mo useDown or MouseUp. See the next section, "Using Button with
MouseMove," fo r more informati on.

Microsoft Visual Basic Programmer's Guide


Chapter 14 Responding to Mouse Events 203

T he reason you can test only which button is used with-MouseDown and MouseUp is that
only one bit is set in Button for each event. Possible binary values of Button are listed below.
Value Meaning
001 (decimal 1) The left button caused the event.
010 (decimal 2) Toe right button caused the event.
100 (decimal 4) The middle button caused the event.

If a button is not present on the user' s mouse, the corresponding bit is always O. On a two-
button mouse, there is a left and right button, but no rniddle button. On a one- button mouse,
there is only a left button.
You can determi ne which button causes a MouseDown or MouseUp eve nt wi th relati vely
simple code. The fo ll owing procedure tests whether Button equ als 1, 2, or 4:
Sub Form_MouseDo wn ( Bu tto n As Integer, Shi ft As Int eger, X As Si ngle,
• Y As Sing l e)
I f Button - 1 The n Prin t "Y ou pressed t he l ef t bu t ton . "
If Bu tton 2 Then Print "Y ou presse d th e right button . "
I f Button 4 Then Pr i nt "Y ou pressed the middl e bu tt on. "
End Sub

If the user presses more than one button, Visual Basic interprets th at action as two or more
separate MouseDown events. It sets the bit for the first button pressed, prints the "You
pressed ... " message for that button , and then does the same for the next button. Simil arl y,
Visual Basic interprets the release of two or more buttons as separate MouseU p eve nts.

Using Button with MouseMove


For the MouseMove event, Button indi cates the complete state of the mouse buttons - not
just whi ch button caused the event, as with MouseDown and MouseUp. It prov ides more
complete informati on because so rne, ali , or none of the bits can be set - notjust one bit per
event, as wi th Mo useDown and MouseUp.
Other binary values are listed below.
Value Meaning
111 (deci mal 7) All three buttons are pressed.
011 (decimal 3) Left and ri ght buttons pressed, not middle.
000 (decimal O) No buttons are pressed.

Thus, for MouseMove, if you test for eq uality to 001 (decimal 1), you're test ing to see if
only the left mouse button is held down while the mouse is moved. If another button is held
down along with the left button, this code doesn' t print anything:
Sub Form_Mouse Move ( Butto n As I nteger . Shi ft As Integer. X As Si ngl e .
• Y As Single)
If Button - 1 Then Pr i nt "Y ou pres s ed only the left button . "
End Sub

Microsoft Visua l Basic Programmer's Guide


204 Part 3 Appli cation- Building Techniques

If you want to test for whether a particular button is down, but you want to ignore whether or
not the other buttons are pressed, use the And operator. This code prints the message for
each button pressed, regardless of whether another button is pressed:
Sub Form_MouseMove (Button As Integer, Shift As Integer , X As Single,
• Y As Si ngle)
If Button And 1 Then Print "You're pressing the left button."
If Button And 2 Then Print "You're pressing the right button."
End Sub

Y ou can test for two buttons being pressed simultaneously by adding another line of code:
Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single,
• Y As Single)
If Button And 1 Then Print "You're pressing the left button. "
If Button And 2 Then Print "You're pressing the right button."
If (Button And 3) = 3 Then Print "You're pressing both buttons."
End Sub

The value of 3 is obtained by adding 1 and 2 together. This produces the binary pattem O11 ,
in which both of the two least-significant bits are set. Using the And operator with 3 masks
out ali bits except the last two and then tests to see if these two bits are set. Testing for
multiple bits is tricky . Note that the following lines produce erroneous results:
If (Button And 1) And (Button And 2) Then
lf Button And 3 Then

There are severa! ways to test for multiple bits . One reliable way is to add the button
con stant s ( 1, 2, or 4) together to produce a single number. Then use the combined And
operator and equality test shown earlier. For example, the following statement tests to see if
ali three buttons are pressed (note that 7 is the sum of 1, 2, and 4) :
I f ( Butt on And 7) = 7 Then Pri nt "Al l three buttons pres sed."

You may find that yo ur code is more readable and easy to maintain if you define constants
for th e buttons you ' re detecting:
Const LEFT_BUTTON = 1
Const RIGHT_BUTTON = 2
Const MIDDLE_BUTTON = 4

Using Both Buttons in the Scribble Application


You can en hance the Scribble application described earlier by usi ng the Button argument.
This version also draws a continuous line when mouse button is pressed and stops drawing
when the button is released. In addition, when the user presses the right button , it draw s a
straight line from the last point drawn .

Microsoft Visual Basic Programmer's Guide


Chapter 14 Responding to Mouse Events 205

Often, it's helpful to note each relevant event and what the application should do in
response. The three relevant events here are mouse events:
• Form_MouseDown- Take a different action depending on state of mouse buttons:
If the left button is down, set DrawNow to True (-1) and reset drawing coordinates.
If the right button is down, draw a line.
• Form_MouseUp - If the left button is up, set DrawNow to False (0) .
• Form_MouseMove - If DrawNow is True (-1), draw a line.

The variable Dr a wNow and the button constants are declared in the Declarations part of the
form:
Dim DrawNow As Integer
Const LEFT_BUTTO N - 1
Const RIGHT_BUTTON - 2

The MouseDown procedure has to take a different action, depending on whether the left or
right mouse button caused the event:
Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single,
• Y As Single)
If Button = LEFT_BUTTON Then
DrawNow = -1
Currentx = X
CurrentY = Y
Elself Button = RIGHT_BUTTON Then
Line-(X, Y)
End I f
End Sub

The MouseUp procedure tums off drawing, but only when the left button is released:
Sub Form_MouseUp (Button As Integer, Shift As Integer, X As Single,
• Y As Single)
If Button LEFT BUTTON Then DrawNow = 0
End Sub

Note that within the MouseUp procedure, a bit set to 1 indicates that the corresponding
mouse button is released.
The MouseMove procedure is ídentical to the one in the previous version:
Sub Form_MouseMove (Button As Integer , Shift As Integer, X As Single,
• Y As Single)
If DrawNow Then Line -(X, Y)
End Sub

Microsoft Visual Basic Programmer's Guide


21)6 Part 3 Application -Building Techniques

Detecting SHIFT, CTRL, and ALT States


You use the argument Shift in roughly the same way you use Button. lf the SHIFT key is
pressed, Shift is 1; if the CTRL key is pressed, Shift is 2; and if the ALT key is pressed, Shift 1s
4. To determine combinations of these keys , use the total of these values. For example, if
SHIFT and ALT are pressed, Shift equals 1 +4, or 5.

The three least-significant bits in Shift correspond to the state of the SHIFT, CTRL, and AL T
key s, as shown in Figure 14.6.

SHIFT key
CTRL key

ALT key 1

1 º º º º
1

lunused

Most-significant bits Least-significant bits


Figure 14.6 How bits representthe state ofthe SHIFT, CTRL, and ALT keys

Any or all of the bits in Shift are set, depending on the state of the SHIFT, CTRL, and ALT
keys. lf only one key is pressed, the· binary patterns are 001 (decimal 1) for SHIFT, 010
(decimal 2) for CTRL, and 100 (decimal 4) for ALT. If all are pressed, Shift has the binary
pattern 111 (decimal 7) . If only SHIFT and ALT are pressed, Shift has the binary pattern 101
(decimal 5).
As with the argument Button , you can use the And operator to mask out ali bits except the
ones you are interested in testing for:
Sub Form_Mou se Down (Button As Integer. Shift As Int eger, X As Si ngle,
• Y As Single)
If Shift And 1 Then Print "You pressed the SHIFT key ."
If Shift And 2 Then Pr int "You pr ess ed the CTRL key . "
If Shift And 4 Then Print "You pressed the ALT key ."
If (S hift And 3) 3 Then Print "You pres se d both SHIFT and CTRL . "
If (S hift And 5) 5 Then Print "Yo u pre ssed both SHIFT and ALT."
If ( Shift And 6) 6 Then Print "Y ou pres sed both CTRL and AL T."
If (Shif t And 7) 7 Then Print "Y ou pressed SHIFT, CTRL . and ALT . "
End Sub

Microsoft Visual Basic Programmer's Guide


Chapter 14 Responding to Mouse Events 207

Dragging and Dropping


When you design Visual Basic applications, you often drag controls around on the forro. The
drag-and-drop features in Visual Basic enable you to extend this ability to the user at run
time. The action of holding a mouse button down and moving a control is called "dragging,"
and the action of releasing the button is called "dropping."
The drag-and-drop capability extends to multiple-form operations. The user can drag the
control anywhere on the screen, including other forros. You can respond to any drag
operation as long as the destination is somewhere within your application.
As the user drags a control, Visual Basic provides a gray outline that moves with the mouse
pointer, as shown in Figure 14.7.

1m forml aa

Figure 14.7 Dragging a control at run time

Note Run-time dragging of a control does not automatically change the location of the
control. You can cause this to happen, but you must program the relocation yourself, as
described in the section "Causing Control Movement" later in this chapter. Often, dragging
is used only to indicate that sorne action should be performed , and the control retains its
original position after the user releases the mouse button.

The following drag-and-drop properties, events, and methods enable you to determine the
meaning of a drag operation as well as how dragging can be initiated (if at all) for any given
control.
Category ltem Description
Properties DragMode Enables automatic or manual dragging of a control.
Draglcon Specifies what icon is displayed when the control is
dragged.
Events DragDrop Recognizes when a control is dropped onto the object.
Dragüver Recognizes when a control is dragged over the object.
Method Drag Starts or stops manual dragging.

All controls except menus and timers can be dragged at run time and share all the properties
li sted above. Forros recognize the DragDrop and Dragüver events, but they don't have the
DragMode and Draglcon properties.

Microsoft Visual Basic Programmer's Guide


208 Part 3 Application-Building Techniques

Enabling Automatic Drag Mode


To enable the user to draga control, set its DragMode property to l. This enables automatic
dragging of the control :
Thing . OragMode = 1

You set the DragMode property to 1 at design time by clicking the arrow at the right of
Settings box and choosing "1 - Automatic."
When you set dragging to Automatic, dragging is always "on." Later, you'll see how to use
the "O- Manual" setting to control dragging.

Note While an automatic drag operation is taking place, the control being dragged does not
recogni ze other mouse events.

Selecting the Drag lcon


As mentioned previously, Visual Basic normally uses a gray outline of the control being
dragged rather than the control itself. You can substitute other images for the outline by
setting the Draglcon property . This property contains an integer that corresponds to a
graphic image. Yo u can ' t set this integer value directly, but yo u can select a graphic image.
The easiest way to set the Draglcon property is to use the Properties bar. After selecting the
Draglcon property, the arrow at the right of the Settings box changes to three dots. Click the
three dots to select a file containing a graphic image from the Load Icon dialog box.
You can assign icons to the Draglcon property from the Icon Library included with Visual
Basic. (The icons are pictured in Appendix B, "Icon Library.") You also can create your
own drag icons with a graphics program. A typical drag icon might be a picture of the
control with its colors inverted .
At run time, you can selecta Draglcon image by assigning the Draglcon property of one
control to the same property of another:
Pic ture l. Oragi con = Pi cture 2 .Dra gi con

You also can set the Draglcon property at run time by assigning the Picture property of one
control to the Draglcon property of another:
Pi ctur e l . Dragi co n = Pi cture 3. Pi ct ur e

Or, you can use the LoadPicture function :


Pict ur el. Dragi co n - LoadPi ctur e( "C: \ic on s \c omput e r \ di s k04.i co")

For more information on the Picture property and the LoadPicture function , see Chapter 13,
"Creating Graphical Effects ," or:

m Search Help for:


Picture

Microso ft Visu al Basic Programmer's Guide


Chapter 14 Responding to Mouse Events 209

Responding When the User Drops the Object


When the user releases the mouse button after dragging a control, Visual Basic generales a
DragDrop event. You can respond to this event in many ways. Dropping may relocate the
control at the new location (indicated by the last position of the gray outline). Remember
that the control doesn't automatically move to the new location .
Two terms are important when discussing drag-and-drop operations-source and target.
They are listed below.
Term Meaning
Source The control being dragged. This control can be any type
except a menu or timer.
Target The object that the user drops the control onto. Thi s object,
which can be a form or control, recognizes the DragDrop
event.

A control becomes the target if the mouse position is within its borders when the button is
released. A form is the target if the pointer is in a blank portion of the form.
The DragDrop event provides three arguments: Source, X, and Y. The argument Source is a
reference to the control that was dropped onto the target. For example, if the user drops a
control onto a blank portion of the form, the Form_DragDrop procedure is invoked:
Sub Form_DragDrop (Source As Control. X As Single, Y As Single)

End Sub

Because So urce is declared As Control, yo u use i t j ust as yo u would a control-you can


refer to its properties or call one of its methods. A useful property in this regard is Tag, a
property to which you can assign any string without causing side effects. Unlike other
properties, Tag is used solely for identification and data storage.
This example assumes that you've set each control's Tag property to the name of the
control:
Su b Form_ DragDrop (Source As Control . X As Sing le, Y As Sing le)
Print Source.Tag; "dropped on background portian of form . "
End Sub

You should show sorne care with the argument Source, because although you know that it
always refers to a control, you don't necessarily know which type of control it is. For
example, if the control is a text box and yo u attem pt to re fer to So u re e . Val u e, the result is
a run-time error because text boxes have no Value property.
You can use the If... Then ...Else Statement with the TypeOf keyword to determine what
kind of control was dropped. For more inforrnation, see Chapter 17, "Advanced Language
Features," or:

Search Help for:


111 TypeOf

Microsoft Visual Basic Programmer's Guide


210 Part 3 Application - Build ing Techniques

All the possible types for Source (ali control types except menus and timers) have a Visible
property. Therefore, you can make a control invisi ble when it's dropped on a certain part of
a form or on another control. The following procedure causes a control to disappear when
it's dropped on a picture box named Yanish:
Sub Vanish _ DragDrop (Sou r ce As Control. X As Single. Y As Single)
Source.Visible = 0
End Sub

Highlighting Objects While Dragging


You may want to highli ght an object as the user drags a control over it. Highlighting informs
the user that if the mouse button is released, the object is dropped in the highlighted area.
This is useful particularly if the drop causes a move or copy operation, or (as in the previous
example) makes something di sappear.
Another way to indicate that a control is over a target is to change the drag icon . You can do
this by changing the Draglcon property of the control being dragged (source control).
To respond to the fact that a dragged control is entering, passing over, or leaving an object,
add statements to the DragOver event. The DragOver event procedure for a form looks like
this:
Sub Form_ Dragüv er (Source As Co ntrol. X As Sing le , Y As Single,
• State As Integer)

End Sub

The DragOver event has the same arguments that DragDrop does. In addition, it has a State
argument which indicates one of the following actions.
Value of State Description
o Enter (the mouse position just entered the object' s borders) .
l Leave (the mouse position just left the object's borders) .
2 Over (the mouse position moved from one part of the object
to another).

Typically, you'll use the Enter and Leave states to create and remove highlighting and
ignore the Over state. Over is useful if you want to know when the mouse position is overa
particular subdivision of an object (such as a region within a picture box) . To respond that
way, you ' d need to evaluate the arguments X and Y, which give the mouse position within
the object.

Mic rosoft Visual Basic Programmer's Guide


Chapter 14 Responding to Mouse Events 211

To create or remove highlighting ·Nith Visual Basic, assign values to BackColor and
possibly ForeColor as well. For example, the following procedure inverts colors when the
user drags a control over Textl (Enter) and inverts colors back to their original state when
the control is dragged off the text box (Leave).
Sub Textl _Dragüver (Source As Control, X As Single, Y As Single,
• State As Integer)
Const ENTER - 0
Const LEAVE - 1
Dim TempColor As Long

If State = ENTER Or State = LEAVE Then


TempColor - Textl.BackColor
Textl.BackColor Textl.ForeColor
Textl.ForeColor = TempColor
End If
End Sub

The constants ENTER, LEA VE, and OVER are defined in the CONSTANT.TXT file.

Controlling When Dragging Starts or Stops


Visual Basic has a Manual setting for the DragMode property that gives you more control
than the Automatic setting. The Manual setting enables you to determine when a control can
be dragged and when it can't. (When DragMode is set to Automatic, the control can always
be dragged as long as the setting isn' t changed.)
For instance, you may want to enable dragging in response to MouseDown and MouseUp
events, or in response to a keyboard or menu command. The Manual setting also enables you
to recognize a MouseDown event befare dragging starts, so that you can record the mouse
position.
To enable dragging from code, leave DragMode in the default setting of Manual (O). Then
use the Drag method whenever you want to begin or stop dragging an object:
[control.]Drag action

If action is 1, the Drag method initiates dragging of the control. If action is 2, the control is
dropped, thus causing a DragDrop event. Giving the value O for action cancels the drag: The
effect is similar to giving the value 2, except that no DragDrop event is recognized.
For example, this statement enables (tums on) dragging of a control named ThisBox:
ThisBox.Drag 1

This statement drops the control and has the same effect as releasing a mouse button:
ThisBox . Drag 2

Microsoft Visual Basic Programmer's Guide


212 Part 3 Application-Building Techniques

Causing Control Movement


You may want the source control to change position after the user releases the mouse button.
This is fairly easy to do when dragging operations do not extend across multiple forms. It is
more complicated when multiple forms are involved. A control created on one form cannot
necessarily appear on another form unless both forms have been designed to have that
control. You may need to use control arrays with these forms, unless you can ensure that the
coñtrol will appear on only one form at a time.
This section describes only control movement on a single form.
To make a control move to the new mouse location, just use the Move method (similar to
the code in the first example in this chap·ter):
Sub Form_OragOrop (Source As Control. X As Single, Y As Single)
Source . Move X, Y
End Sub

This code may not produce precisely the effects you want, because the top left comer of the
control is positioned at the mouse location. This co9e po~ition the cen~~r of the control at
the mouse location: ·
Sub Form_OragOrop (Source As Control. X As Single, Y As Single)
Source.Move (X - Source.Width / 2), (Y - Source.Height / 2)
End Sub

The code works best when the Draglcon property is set to a value other than the default (the
gray rectangle). When the gray rectangle is being used, the user normally wants the control
to move precisely into the final position of the gray rectangle. To cause this action , record
the initial mouse position within the source control. Then use thi s position asan offset when
the control is moved .

To get the initial mouse coordinates:


1 Specify manual dragging of the control.
2 Declare two form-level variables, DragX and DragY .
3 Tum on dragging when a MouseDown event occurs. Also, store the value of X and Y in
the form-level variables in this event
4 Tum off dragging on MouseUp.

The following example illustrates how to cause drag movement for a picture box named
Pictl. The control' s DragMode property should be set to Manual (O) at design time. The
declarations section contains the form-level variables Ora g X and Ora g Y, which record the
initial mouse position within the picture box :
Dim DragX As Single, OragY As Single

Mic rosoft Visual Basic Programmer's Guide


Chapter 14 Responding to Mouse Events 213

The MouseDown and MouseUp procedures for the control turn dragging on and drop the
control , respectively. In addition, the MouseDown procedure records the mouse position
inside the control at the time dragging begins:
Sub Pictl_MouseDown (Button As Integer, Shift As Integer, X As Single.
• Y As Single)
Pictl.Drag 1
DragX X
DragY = Y
End Sub

Sub Pictl _MouseUp (Button As Integer, Shift As Integer, X As Single,


• Y As Single)
Pictl . Drag 2
End Sub

The Form_DragDrop procedure actually moves the control. To simplify this example,
assume that Pict 1 is the only control on the form. The target can therefore only be the form
itself. The Form_DragDrop procedure repositions the control, using DragX and DragY as
offsets:
Sub Form_DragDrop (Source As Control. X As Single, Y As Single)
Source.Move (X - DragX), (Y - DragY)
End Sub

Note that this example assumes that Pictl and the form use the same units in their respective
coordinate systems. If they don ' t, then it's necessary to convert between units.

Microsoft Visual Basic Programmer's Guide


~}.'. .. . . . .~-- -. '' , ... ,·•. . ' ' .~ ' ' - """ .' .' ,. . ; ', . . . ,. . .~ ' . . .. '
,
:· · e h a p t e r 1 5 •
.-

Creating Multiple-Form Applications

Once you know how to write an application with a single forrn, you know almost everything
you need to know to write a multiple-form application. Any Visual Basic application can be
easily extended to have multiple forms. ·
Multiple forms can give your application increased functionality. Each forrn can have its
own unique look and purpose.
Having more than one form in your application is particularly useful if you want to create
custornized dialog boxes. You designa custom dialog box as a forrn. These dialog boxes can
be more complex than the ones you create with InputBox$ or MsgBox. In fact, custornized
dialog boxes can have all the controls and graphics you'd put on other forms.
This chapter shows you how to load, display, and hide different lcinds of forms. The main
sections are:
• Methods and Statements that Handle Forms
• Setting Form Properties
• Designating a Startup Form or Module
• Choosing an Icon
• Loading and Displaying Forms
• Hiding Forms
• Unloading Forrns
• Exiting a Multiple-Form Application


.. •
• •
• •
• •
• •
" •
• •
• •
• • •
• •
• •
• •
• •
• •
• •
"
216 Part 3 Application-Building Techniques

Methods and Statements that Handle Forms


This section provides a brief overview of the methods and statements that manipulate forms.
The rest of the chapter discusses sorne important form properties (especially as they relate to
dialog boxes), but this section may be all you need if you just want a quick reference.
The following Visual Basic keywords handle forms .
Keyword Syntax Description
Load statement Loadform Loads a form into memory ,
so yo u can refer to its
controls and properties;
does not display the form .
Show method [fon11.]Show Displays a form ; if the
[m odalsta/eo/o J form is not yet lo aded,
Show loads it first. If
modalstate is 1, the user
cannot work with other
forms while form is
displayed.
Hide method [fonn.] Hide Hides a form. You still can
refer to the form's control s
and properties.
Unload statement Unloadform Remo ves (el oses) a form
from memory and the
screen .

When you create a multiple-form app li ca ti on, you may want the code attached to one form
to refer to something on another form. Or you may want to place a general procedure in a
module, so that more than one form can use it. In both cases, it 's necessary to qualify
references to form s. (In single-form appli ca ti ons with no modules, the form is implicit.)
To refer to a property of another form , use thi s syntax :
form.prop erty

To refer to a property of a control , use thi s syntax :


form. control.prop erty

Theform and control can be any valid refe re nce to a form or control. The property is always
a name of a property supported for th at obj ec t.

M ic rosoft Visual Basic Programmer 's Guide


Chapter 15 Creating Multiple-Form Applications 217

Setting Form Properties


Customized dialog boxes are a good reason to add forros to your application You can create
a dialog box in much the same way you create any other kind of form: You choose the New
Form command from the File menu, then design the formas you normally would. You' ll
also want to set the form properties, as explained in the section "Setting Properties for
Dialog Boxes."
Dialog boxes are characterized by the fact that they temporarily display or get information
from the user; then they are closed. These forms should be modal (the user has to close them
before working with other forms) and not resizable by the user. Other kinds of forms can be
thought of as general-purpose forms.

Setting Properties for General-Purpose Forms


The form shown in Figure 15.1 is from the Rock 'n' Roll application that's used asan
example throughout this chapter. The form displays a picture of the Beatles and provides
buttons that enable you to get more information.

Forms with captions


can be moved.

·r . . ·· ; . ~ _;; . :

1
. ·J/iU .;;ii/1fiJ l!/ 1ii 11 l
: : . : ; ,-•, ; ; One of the most inlluential rock groups ever.
Command
buttons
: : : : : : : : :r Members include Paul McCartney, Ringo Starr,
. ~ :f ¡_: ~ ;• John Lennon .. George Hanison
! .
: : : ·:· ::' : • • : 1 ~ ••• : : ; • : : • : : : .. : :

Lab el 1 Form 's size can be changed.


Figure 15.1 The Beatles Form

Microsoft Visual Basic Programmer's Guide


218 Part 3 Application-Building Techniques

Note Not all of the material you need for the Rock ' n' Roll application is included in this
chapter, but it may be helpful to create and run its forms.

If users are running several Windows applications, it's likely they ' ll want a lot of control
over how much room the Beatles form takes up on their screen . They may want to shrink the
fo rm to an icon while they run another Windows application. Or they may want to move the
form or make it smaller or larger.
The properties listed below for the Beatles form are typical of many windows in Windows
applications. Except for the last two properties listed (Caption and FormName), the settings
are the defaults for the property . That means th e properties start off with the followin g
settings.
Form property Setting Reason for setting
BorderStyle 2 - Sizeable Because BorderStyle is set to "2," users can change
the size of this window.
MinButton True Users can shrink the window to an icon so they can
view another application on their screen - and then
enlarge the Beatles window later.
MaxButton True Enables users to enlarge this window to a ful] screen.
ControlBox True Adds a Control menu, which provides Restore, Move,
Size, Minirnize, and Maximize commands . Helpful to
ali users, this menu is essential for users who don ' t
have a mouse.
Caption The Beatles Iden tifies the window and appears on the title bar.
Any window with a caption can be moved.
FormName Beatles Sets the name that will be referred to in code.

For more details on form properties, see the Language Refe rence, or:

m Search Help for:


form

Setting Properties for Dialog Boxes


The dialog box in Figure 15.2 from the Rock ' n' Roll application enables the user to choose
a rock group. This lets the application know which form to display next.
Generally, a user responds to a di alog box immediately and the dialog box is closed.
Because a dialog box is temporary, users normally have no need to change its size, shrink it
to an icon, or expand it. However, yo u may want to make di alog boxes movable -
es pec iall y if there's a chance that your di alog box may hide important information on the
sc reen.

Mic rosoft Visua l Basic Programmer's Guide


Chapter 15 Crea ting Multip le -Form Appli cations 219

No Minimize ar
Maximize buttons

Choose a rock group: _ _---tt-- Labe/


Beatles
o ·o ors
Fleetwood Mac
J ackson Five
Jeflerson Airplane
Pink Floyd
---1-- List box
Rolling Stones
Supremes
TheWho

Double -/ine border shows that


form 's size can 't be changed.
Figure 15.2 The GroupChoice form is a dialog box.

The properties for the GroupChoice dialog box are set as follows:
Form property Setting Reason for setting
BorderStyle 3 - Fixed Users don ' t need to change the size of the form.
Double
MinButton False Users don't need to shrink the dialog box toan icon.
MaxButton False Users don ' t need to enlarge the dialog box to a full
screen.
ControlBox True Adds a Control menu, which makes the Move
command accessible from the keyboard . (The
Restare, Size, Minimize, and Maximize commands
will appear on the Control menu, but these
commands will be disabled.)
Caption Rock Groups Identifies the dialog box .
FormName GroupChoice Sets the name that will be referred to in code.

Note The settings you specify for MaxButton, MinButton, BorderStyle, and ControlBox
are not reflected in the form's appearance until you run the application.

Simple Dialog Boxes


In sorne cases, all you need is a very simple dialog box. To avoid designing dialog box
forms and setting properties, you can create dialog boxes with the InputBox$ function , or
the MsgBox statement or function.

Microsoft Visual Basic Programmer's Guide


220 Part 3 Applícatíon-Buíldíng Techníques

Far more information on lnputBox$, see Chapter 11, "Getting lnformation from the U ser."
Far information on MsgBox, see Chapter 12, "Displaying and Printing lnformation"; the
Language Reference; or:

m Search Help for:


dialog

Designating a Startup Form or Module


Every application must begin with a startup form ora startup module. With a multiple-form
application, it's important to decide which form should load first.
By default, Visual Basic selects the first form placed in the project as the startup form. To
select another form, choose Set Startup Form from the Run menu . Only one form can be
loaded automatically this way. Ali other forms must be loaded explicitly using the Load
statement or Show method.
You also can create a startup module by writing a general procedure called Main. When a
module-leve! procedure called Main is present, Visual Basic invokes this procedure when
the application is run; it does not load any form automatically.
The Rock 'n' Roll application starts with the Welcome form shown in Figure 15.3, a
window that introduces users to the application .

Figure 15.3 The Welcome form is the startup form .

Microsoft Visual Basic Programmer's Guide


Chapter 15 Creating Multiple-Form Applications 221

This form uses the default property settings, with the fo1lowing exceptions.
Form property Setting
FormName Welcome
Caption Rock 'n' Roll App
Picture \ROCK\WELCOME.BMP

Note that by default, BorderStyle is set to Sizeable, and ControlBox, MaxButton, and
MinButton all are set to True.
You use the Settings box on the Properties bar to set the Picture property, which identifies
the file containing the background picture. (Toe \ROCK\WELCOME.BMP path given for
Picture in the table is fictitious.) When you select the Pícture property in the Properties list
box , the arrow at the right of the Settings box becomes three dots; click them to open a
dialog box from which you can selecta picture file.
You also can paste a picture onto a form via the Clip board. For more information, see
Chapter 13, "Creating Graphical Effects."

Choosing an lcon
When the user minimizes a form, an icon is displayed that represents it. You can use the
Visual Basic standard icon, or you can customize your applícatíon by selecting your own
icon for each form. The icon is specified by the Icon property of a form.
To specify an icon, select the !con property in the Properties list box, then click the three
dots at the right of the Settings box. Choose the .ICO file that contaíns the ícon you want.
Figure 15 .4 shows the Visual Basic standard icon and the custom icon used for the Welcome
form. The !con property for the Welcome form is set to the filename MISC31.ICO (a
musical scale) in the !con Library included with Visual Basic. (The full path depends on
where you installed Visual Basic.)

Mi,fyft
•~7-.._
~z~~
Visual Basic Rock 'n' Roll .6.pp
Figure 15.4 Visual Basic standard icon and the icon for the Welcome form

Note The graphics file you choose for your icon must have the .ICO format. The Visual
Basic !con Library is a good source of icons for your forms.

Microsoft Visual Basic Programmer's Guide


m Part 3 Application-Building Techniques

Loading and Displaying Forms


Although the startup form loads automatically when you start a Visual Basic application,
you'll use Visual Basic statements and methods to load and display other forms .
The Show method provides a convenient way to load and display any form in your
application. If a form is already loaded but not displayed, Show displays it. If a form is not
loaded, Show both loads it and displays it. The Show method uses this syntax:
[form.]Show [modalstate o/o]

The argument modalstate is an integer value that specifies whether or not the form is modal.
If modalstate is 1, the form is modal. If modalstate is O or is omitted, the form is modeless.
Once a modal form is displayed, the user cannot switch focus to another window until the
form is closed. Furthermore, no Visual Basic code is executed until that form is hidden or
unloaded. Dialog boxes are usually modal.
When loading a form, Visual Basic sets the form 's properties to their initial values (specified
at design time) and executes the Form_Load procedure attached to that form. The
Form_Load procedure may do additional initialization beyond what could be set in the
Properties bar.

Note Any reference to a form's controls or properties causes Visual Basic to automatically
load a form into memory, if it is not loaded already.

For more information on the Show method, see the Language Reference, or:

Search Help for:


111 show

'11icrosoft Visual Basic Programmer's Guide


Chapter 15 Creating Multiple-Form Applications 223

Displaying the GroupChoice Form


From the Welcome form, the user can choose the Rock Groups command button. Choosing
this command button displays a dialog box, which is another form named GroupChoice, as
shown in Figure 15.5.

Beatles
Doors
Fleetwood Mac
Jackson Five
Jeflerson Airplane
Pink Floyd
Aolling Stones
Supremes
The'Who

Figure 15.5 The GroupChoice Form

Clicking the Rock Groups command button invokes its Click event procedure, which
displays and loads the GroupChoice form :
Sub RockGroups _Click ()
GroupChoice.Show
End Sub

To add controls to the GroupChoice form shown in Figure 15.5, create a label and set its
caption to "Choose a rock group:". Then create a list box (named GroupChoice) large
enough to hold six or more items.

Microsoft Visual Basic Programmer's Guide


224 Part 3 Applic ation-Building Techniques

As soon as the GroupChoice fonn loads, its Load procedure is invoked, which places the
names of the rock groups into the li st box named GroupLi st:
Sub Form_Load
Grouplist.Addltem "Beatles"
Grouplist.Addltem "Door s "
Grouplist.Addltem "Fleetwood Mac"
-Groupl i st.Addltem "Jackson Fi ve"
Grouplist.Addltem "Jefferson Airplane"
Grouplist.Addltem "Pink Floyd"
Grouplist.Addltem "Rolling Ston es "
Grouplist.Addltem "Supreme s "
Groupli st.Addltem "The Who"
End Sub

Hiding Forms
With multiple-form applications, you often may want to hide the form that's currently on the
screen and display a new one. If there's a chance you want to use the form later, you ' ll
improve execution speed by temporarily hiding a form rather tban unloading it.
Another advantage to temporarily hiding a form (ratber than unloading it) is that you don ' t
lose any data attached to the form , such as property values and data stored in form-level
variables.
To hide a form that 's already been loaded, use the Hide method . The syntax is:
[form.]Hide

For example, thi s proced ure hides the Welcome form after the user chooses any item in the
GroupList list box :
Sub Grouplist_DblClick ()
Welcome .Hide
End Sub

If Welcome is a form that you may use again soon, then it makes sense to hide the form
rather th an unload it. You can display the form again by using the Show method :
Welcome.Show

For more information on the Hide method , see the Language Reference, or:

m Search Help for:


hide

Hiding the Welcome and GroupChoice Forms


Wh en the use r chooses "Beatles" from th e li st box on th e GroupChoice fonn , the app1icat ion
hid es the Welcome and GroupC hoice for ms and di splays th e Beatles fo rm .

Micros oft Visual Basic Programmer's Guide


Chapter 15 Creating Multiple-Form Applications 225

The user can choose a rock group from the GroupChoice form by double-clicking a list item.
The code for the GroupList_DblClick event procedure is:
Sub Grouplist_DblClick ()
Welcome.Hide
GroupChoice.Hide
Select Case Grouplist.Listindex
Case 0
Beatles.Show
Case 1
Doors.Show
Case 2
FleetMac.Show
Case 3
JackFive.Show
Case 4
JeffAirplane.Show
Case 5
PinkFloyd.Show
Case 6
Stones.Show
Case 7
Supremes.Show
Case 8
Who.Show
End Select
End Sub

Checking to See if a Form Is Hidden


Your application can check to see if a form is visible or hidden by checking the setting of the
Visible property, which retums True (-1) if the form is visible and False (0) if it is hidden.
The Visible property applies not only to forms but also to ali controls other than timers.
For example, these statements hide the Beatles form if it is not already hidden:
If Beatles.Visible Then
Beatles.Hide
End If

Loading a Form Without Displaying lt


Sometimes you may want to refer to properties and controls of a form without actually
displaying it. Or you may want to load severa] forms upon startup but make them hidden;
later you can display them when appropriate. This technique is an altemative to loading
forms while you are running the application, and it speeds up response time to the user.
However, keeping many forms loaded requires more memory.
In these cases, the Load statement is useful because it loads a form into memory without
putting it on the screen.

Microsoft Visual Basic Programmer's Guide


226 Part 3 Application-Building Techniques

For example, to load the Beatles form without displaying it, use this statement:
Load Beatles

The Load statement sets a form ' s properties to their initial values and executes its
Form_Load procedure. For more information on the Load statement, see the Language
Reference, or:

m Search Help for:


Load

Unloading Forms
You can unload form s when you no longer need them. When you unload a forrn , the form is
removed frorn the screen and from memory; you can no longer refer to any of its properties
or controls. Any data stored in the form is lost unless you have saved it to a file (as
explained in Chapter 21, "Processing Files"). For exarnple, this statement unloads the
Welcome form:
Unload Welcome

If there' s a chance you may want to use the form later, you may want to use the Hide
method instead. Hiding a form stores it in memory; this makes greater demands on memory
but can improve response time later on. Conversely, unloading a form frees up memory but
requires that you load the form again when you want to reuse it.
For more information on the Unload statement, see the Language Reference , or:

m Search Help for:


Unload

Exiting a Multiple-Form Application


A Visual Basic application stops running when ali forms are closed and no code is being
executed .
To close the application from within Vi sual Basic code, you can either unload every form
one by one, or use the End statement. This statement stops execution of all code in your
a¡,¡-l i~· ati ,lll <11HI l· lo,n .iil) 1ik,) o u llld'. lid._. ,,¡x· 11:.:.: . :\ u: .._ thal tlic End c. la lt.:lli é lll vv u rkc.
only in executable files .
For example, the Rock ' n' Roll application includes a Quit command button . The following
Click procedure is attached .to this command button :
Sub Quit_Click ()
End
End Sub

Note that when you close an application thi s way, no Form_Unload procedures get called. A
Form_ Unload procedure is called only if you explic itl y unload a form.

Micro soft Visual Basic Programmer's Guide


Debugging

Visual Basic provides tools to analyze how your application behaves. These are called
debugging tools because they are particularly useful in locating the source of bugs (errors) .
Debugging support includes breakpoints, single stepping, and the ability to display the
values of variables and properties. These are fairly standard debugging techniques. Visual
Basic also includes special capabilities, sorne of which are inherited from Microsoft
QuickBasic: edit-and-continue capability, setting the next statement to be executed, and
testing procedures while halted. Plus, Visual Basic enables you to examine what happens to
property settings.
This chapter shows how to use the debugging tools included in Visual Basic. The main
sections are:
• Approaches to Debugging
• Design T~e, Run Time, and Break Mode
Halting Execution at a Problem Statem~nt
• Running Selected Portions of Your Application
• Testing Data and Procedures with the lmmediate Window
• Special Considerations in Debugging Events
• Testing and Using Command-Line Arguments
228 Part 3 Application -Building Techniques

Approaches to Debugging
The debugg ing techniques presented in thi s chapter are actually a set of analysis tool s.
Vi sual Basic cannot diagnose and fix all of your errors far you , but it does provide tools to
analyze how execution flows from one part of the application to another, and how variables
and property settings change as statements are executed. Debugging tool s are a way of
looking inside your application; they can help you determine what happens and why.
To understand how this is useful, consider the three kinds of errors you can encounter:
• Syntax errors . These errors are the result of a statement that is incorrectly constructed.
You may have mistyped a keyword,- omitted sorne necessary punctuation, or forgotten to
balance pairs of If and End If statements. Visual Basic detects these errors as soon as
they are entered in the Code window.
• Run -rime errors. These erro rs occur (and are detected by Vi sual Bas ic) whe n a statement
attempts an operation that is impossible to carry out. A good example is division by zero.
Suppose you have this statement;
Speed = Mi les / Hour s

If Ho u r s contains zero, the division is an invalid operation, even though the stateinent
itself is syntactically correct. The application must run befare it can detect thi s error. Not
all run-time errors are easily fixed . For example, a "Disk ful! " error is a problem you
can ' t foresee when writing the application. For information on dealing with this kind of
error, see Chapter 19, "Handling Run-Time Errors."
• Program logic errors. An application is not really correct unless it performs the way it
was intended to. An application can have syntactically valid code, run without
pe1fo rmin g any invalid operations, and yet produce incorrect results. Onl y by tes tin g the
application and analyzing results can you verify that the application is performin g
correc tly .

Debugging tool s are designed to help you with the last category - program logic errors,
which can be far more elusive tlían syntax errors or run-time errors. For instance, an
incoITect result may be produced at the end of a long series of calculation s. In debugging,
the task is to determine where something went wrong. Perhaps you forgot to initialize a
vari able, chose the wrong operator, or used the wrong formula somewhere.
There are no magic tricks to debugging, and there is no fixed sequence of steps that works
every time. Bas icall y. debu gg ing in volves understanding what's go ing on durin g runn ing of
the appltcaLion . rhe be LLer yo u understand how your appli cation works, the fas ter yo u can
find a bug. Debugging is easier if you :
• Design your applications carefully by writing down the relevant events and how your
code will respond to each one. Give each event procedure and each general procedure a
specific, well-defined purpose.
• Include numerous comments. As you go back and analyze your code, you ' 11 understand it
much better if the purpose of each procedure is stated in comments.

Microsoft Visual Basic Programmer's Guide


Chapter 16 0ebugging 229

• Develop a consistent naming scheme for the variables in your application. One of the
most common sources of errors is mistyping a variable narne. Visual Basic creates an
implicitly defined local variable if it can't find a matching declaration.
1111 When your application doesn't produce correct results, browse through the code and try
to find statements that may have caused the problem. Set breakpoints at these statements
and restart the application. Breakpoints are described in the section "Halting Execution at
a Problem Statement" later in this chapter.
• When the program halts, test the values of important values and properties. With Visual
Basic, you use the Immediate window to examine variables and expressions.

esign Time, Run Time, and Break Mode


To test and debug an application, you need to understand which of three modes you are in at
any given time. You have already used Visual Basic in design time while creating an
application and in run time while running it. This chapter introduces break mode, in which
you can examine and alter data while running of the prograrn is suspended.

Note The Visual Basic title bar (iust above the Properties bar) always shows you which
mode you are in, by displaying "[design]," "[run]," or " [break]."

The characteristics of the three modes are listed below.


Mode Description
Design Most of the work of creating an application is done here. Y ou can
design forms, draw controls, write code, and use the Properties bar
to set or view property settings. You cannot execute code or use
debugging tools, except for setting breakpoints .
Choose Start from the Run menu to switch to run time. (Y ou cannot
switch directly to break mode.)
Run The application code (procedure) takes control. You interact with
the application the way the user would. You can view code but
cannot change it.
Choose End from the Run menu to switch back to design time.
r · D. 1
"' th r R11n 111 c nu 0 1• '.",. , , , , ''TI." ~ 1"·'' \ h · '" ,. ·h tn
break rnode.
Break Execution is suspended while running the application. You can view
and edit code (by choosing View Code from the View menu) ,
examine data, restart the application, end exec ution, or continue
from the same point.
Breakpoints can be set at design time and run time, but other
debugg ing tools work on ly in break mode .

Microsoft Visual Basic Programmer's Guide


230 Part 3 Application -Building Techniques

Break mode enables you to both edit code and run it. Before you entera new statement, you
can first test its effects by entering it in the Immediate window. The Immediate window has
a number of uses, the most common of which is to evaluate variables and property settings .
Whenever you enter break mode, execution has stopped at a particular statement. The
variable and property settings are retained, so you can use the Immediate window to analyze
the exact state of the application at that point.
Once in break mode, you can start running your application again by choosing Continue
from the Run menu . This command resumes execution from the last point at which it
stopped. Y ou can retum to design time by choosing End from the Run menu .
The nex t section describes theways of entering break mode when your application is
runnmg.

Halting Execution ata Problem Statement


To use debugging tools, you'll first need to enter break mode. But you don't want to enter
break mode at a random location; instead, you want the application to halt at a place in the
code that' s likely to have caused the problem. This is why Visual Basic provides breakpoints
and Stop statements. A breakpoint is a statement at which Visual Basic automatically stops
execution, putting the application in break mode.
Visual Basic stops execution ata line of code when any of the following things happen :
• A statement on that line generales a run-time error.
• You se t a breakpoint at that line.
• You placed a Stop statement on that line.

The applicati on also switches into break mode if, during running of the application, you
press CTRL+BREAK or choose Break from the Run menu. It's possible to break execution
when th e applica tion is idle (when· it is between processing of events); when this happens,
execution does not stop ata specific line, but Visual Basic switches to break mode anyway .

Fixing a Run-Time Error and Continuing


Sorne run-time errors result from simple oversights when entering code, and are easily fixed .
Type mi smatches that involve properties are run-time errors-for example, you refer to
MyControl.Text, but MyControl <loes not have a Text property.

Microsoft Visual Basic Programmer's Guide


Chapter 16 Debugging 231

Figure 16.1 shows a run-time error message.

Forml
Object: IForm li] Proc: 1Click w
Sub Form Click () •
A~%-= Ual(AgeText.Text)
liZ!litiffi - RestRateText. Textl
TrainRate% = ((220 - Age% - RestRate%) * .65) + RestR
Readout.Text.Text = Str$(TrainRate%) + "beats per min
End Sub
Microsoft Visual Basic

(1) Type mismatch

¡OK¡
+
+ +

Figure 16.1 Run-time errors such as "Type mismatch" halt execution.

In the case of the type mismatch, the solution is to fix the problem statement so that it places
the correct type of data (numeric) into the variable Res t Ra te%:
RestRate% = Val (RestRateT ext .Te xt)

Then you can continue program execution from the same place it halted, even though you've
changed sorne of the code; just choose Continue from the Run menu. As you continue
running the application, you can see if the problem is fixed. Sorne changes (most commonly,
changes in variable declarations) do require the application to start over again; but when this
happens, Visual Basic notifies you that you must restart the application.

Using a Breakpoint to Selectively Stop Execution


A breakpoint tells Visual Basic to halt just before a specific line of code. When Visual Basic
is executing a procedure and it encounters a line of code with a breakpoint, it switches into
break mode.
You can set or remove a breakpoint in break mode or at design time.

To set a breakpoint:
Tn th c Code window. movc thc i11<..crt ;1rn point to a lin c of codc that does not airead y ha,·c
a breakpoint.
2 From the Run menu, choose Toggle Breakpoint.
-or-
Press F9.
Visual Basic displays the selected line in bold.

Microsoft Visual Basic Programmer's Guide


232 Part 3 Application-Building Techniques

To clear a breakpoint:
1 In the Code window, move the insertion point to a line of code that has a breakpoint (the
line is di spl ayed in bold).
2 From the Run menu , choose Toggle Breakpoint.
- or-
Press F9 .
Visual B asic displays the selected line in a plain font.

For exampl e, Figure 16.2 show s a procedure halted at the third line, which has a breakpoint.
Note the rectangular outline around the statem ent at which the procedure halted. This o utline
indicates the next statement to be execu ted ; thi s is called the current statement.

Sub Form Click () •


A e%-= Ual(A eTExt.Text)
RestRate~ = Ual(RestRateTExt_Text) Breakpoint is in bold.
TrainRate% = ((220 - Age% - RestRate%) * .65) + RestR
Readout.Text = Str$(TrainRate%) + " beats per minute" Rectangular outline
End Sub indicates it is the
current statement.

Figure 16.2 A procedure halted by a brea kpoint

Once a breakpoint is reached and the appli cation is halted, you can examine what 's
happened up to tha t point. Examining results of the application is easy, because yo u can
move the focus back and forth be tween th e form of your application and the Code window.
lf 1he rrohlem yn11 ~re lnokin !:! for 1-w; alrcacly nccu rrecl . th en you know a rrc\ io u, !:,-
execu ted line of code caused the problem . lf not, then sorne line of code not yet exec uted is
ca usin g the problem .
R eme mber that when a breakpoint occ urs, th e application stops just before th at I in e is
exec uted. Therefore, if the line of code wi th th e breakpoi nt is responsible for th e probl e m,
you won ' t see the problem until yo u exec ute at least one more statement. Single stepping ,
di sc ussed later in thi s chapter, may be h elpful to yo u in thi s regare! .

Mic rosoft Visual Basic Programmer's Guide


Chapter 16 Debugging 233

A word of caution: Although no line of code has directly caused the problem, a statement
may indirectly be at fault, because it assigns an incorrect value to a variable. You may want
to examine the value of variables and properties whüe in break mode. The section "Testing
Data and Procedures in the Immediate Window" later in this chapter explains how to do that.

Creating Breakpoints with Stop Statements


Placing the Stop statement in a procedure is an alternative to setting a breakpoint: Visual
Basic halts execution and switches to break mode whenever it encounters a Stop statement.
In effect, a Stop statement is a breakpoint, but it is not set or cleared the same way.

Note There is one important difference between a Stop statement and a breakpoint. If you
leave the current project (or leave Visual Basic) and then load it again, all breakpoints are
cleared. Stop statements are more permanent; they stay in the code until you remove th em.

Remember that (unlike tbe End statement, which terrninates all execution) a Stop statement
does nothing more than temporarily halt execution. You can always choose Continue from
the Run menu to resume running the application.
For more information on the Stop statement, see the Language Reference, or:

Search Help for:


111 Stop

Running Selected Portions of Vour A_


pplication
lf you know exactly which statement caused an error, the use of a single breakpoint may be
sufficieot. More often, however, you can only guess the general vicinity of the statement that
caused the error. A breakpoint helps you get to that general area. Once there, you can use
single stepping and procedure stepping to see the effect of each statement. You also can skip
over statements or back up by starting execution at a new line. (Stepping throu gh statements
is sometimes referred to as "tracing.")

Single Stepping Through Statements


Single stepping is the process of executing one statement ata time. After steppin g throu gh
each stíl tement , yo u can see its effect by looking at yo ur application's forms .

To step through codea statement ata time:


• From the Run menu, choose Single Step. ,
- Or -
• Press F8 .

Microsoft Visual Basic Programmer's Guide


234 Part 3 Application-Builsing Techniques

During a single-step command, Visual Basic temporarily switches into run time and
executes the current statement. Then it switches back to break mode and advances to the
next statement.

Note A line of code can contain two or more statements, separated by a colon(:). Visual
Basic uses a rectangular outline to indicate which of the statements to execute next. Unli ke
the Microsoft CodeView debugger and most other debugging tools , Visual Basic enables
you to single step between individual statements, even if they are on the same line.
However, breakpoints are always set on the first statement of a line.

Procedure Stepping
Procedure stepping is identical to single stepping, except when the current statement
contains a call to a procedure. The Single Step command steps through each line of the
procedure that was called, but the Procedure Step command executes the called procedure as
a unit and then steps to the next- statement in the current procedure. For example, suppose
the statement calls the procedure SetAlarmTime:
SetAlarmTime 11, 30, 0

If you choose the Single Step command, the Code window displays the SetAlarmTime
procedure and sets the current statement to the beginning of that procedure. This is the best
choice if you want to analyze the code within SetAlarmTime.
If you use the Procedure Step command, the Code window continues to di splay the current
procedure. Execution advances to the statement immediately after the call to SetAlam1Time.
Thi s is th e best choice if you want to stay at the same level of code and don ' t need to
analyze how SetAlarmTime works.
Y ou can freely altemate between the Single Step and Procedure Step commands . The
command you use depends on which portions of code you want to anal yze at any given time.

To use procedure stepping:


• Choose Procedure Step from the Run menu.
- Or -
• Press SHIFT+F8 .

Setting the Next Statement to Be Executed


When you know a certain section of code is causing trouble, you may want to skip over it.
Doing so doesn' t salve the problem, of course - eventually, you' ll have to come back and
debug that section. However, skipping lines of code enables you to move on and examine
other parts of the application.
At other times, you may want to start execution ata previous line. Perhaps you have
chan ged th e value of a variable or property and want to see if the code will produce different
res ults with thi s data.

Microsoft Visual Ba sic Programmer's Guide


Chapter 16 Debugging 235

Visual Basic enables you to start execution at a different line of code as long as it is within
the same procedure.

To set the next statement to be executed:


1 Move the insertion point to the line of code where you want execution to start next.
2 From the Run menu, choose Set Next Statement.
Then, if you want to resume execution, choose Continue from the Run menu.

Note You must be in break mode to set the next statement to be executed. The Set Next
Statement command is not available at design time or run time.

Testi ng Data and Procedures in the lmmediate Window


Sometimes you can find the cause of á problem by executing portions of code. But more
often you'll have to analyze what's happening to the data as well. For example, suppose the
background of your form tums purple when it should tum white. You rnight isolate the
problem to a single statement:
BackColor - MyFormColor

Y ou are clearly not done, however. First, you must determine what the val ue of
My Fo rmC o 1 o r was just befare the statement was executed. Second, yo u must determine
where My Fo rmC o l o r was assigned the incorrect value.
Examining the values of variables and properties is a common use for the Immediate
window. In addition, you also can use the Immediate window to assign values, evaluare
expressions, and test procedures .
There are two ways to print to the Immediate window: by placing statements in the code for
your application, or by entering a statement in the Immediate window itself.

Printing from Application Code


The Print method sends output to the Immediate window whenever you prefix it with the
special Debug object:
Debug.Print [items] [;]

For example, the following statement prints the value of Sal a ry to the Immediate window
every time it is executed:
Debug.Print "Salary - " ; Salary

This technique works best when there is a key place in your application code at which the
variable (in this case, S a 1 ar y) is known to change. For example, yo u mjght put the previous
statement in a loop that repeatedly alters Sal ary .

Microsoft Visual Basic Programmer's Guide


236 Part 3 Application -Bu ild ing Techni ques

This technique has a couple of adv antages. First, yo u don ' t have to break execution to get
feedback on performance. You can see data or other messages displayed as yo u run the
appli cation. Another advantage is that th e feedback is di spl ayed in a separate area (the
Immediate window) , so that it does not interfere with output intended for users to see.
For more information on the Debug object, see the Language Ref erence, or:

Search Help for:


111 Debug object

Printing from Within the lmmediate Window


Once you' re in break mode, move the foc us to the Immediate window to examine data. To
do so, either click the Immedi ate window (if visible) or choose lmmediate Window fro m the
Window menu. You then can use the Print rneth od witho ut the Debug prefi x. Type or paste
in a statement, press ENTER. and the Immediate window responds by carrying out the
statement, as shown in Figure 16.3.

Responses from Visual Basic


Figure 16.3 The lmmed iate Window

A ques ti on mark (?) is useful shorthand fo r the Print keyword. The question mark means
precisely the same thing as Print and can be used in any co ntext Print is used. For example,
the examples above coul d be entered as shown in Fig ure 16.4.

Responses from Visua l Bas,c


Figure 16.4 Using a qu estion ma rk to print to the lmmed iate window

Mic rosoft Visual Basic Progra mmer's Guide


Chapter 16 Oebugging 237

Note that you can di splay variables only if they have the appropriate scope relative to the
current statement. Whenever Visual Basic enters break mode, the Code window comes to
the foreground , identifying:
• The currently executing form or module (indicated in the Code window' s title bar) .
• The currently executing procedure (displayed in the window).
• The next statement to be executed (identified by a rectangular outline) .

In addition, the title bar of the Immediate window indicates what the current form or module
is. This way you always know which form or module is current, even if you move the focus
between different Code windows.
The current procedure, form, and module determine what variables can be displayed
according to the scoping rules presented in Chapter 9, "Language Elements." For example,
suppose the Immediate window indicates th at Form 1 is the current form . In thi s case, you
can display any of the form-level variables of Forrnl. You also can display local variables of
the procedure displayed in the Code window. But you can' t display variables of other forms
and modules.

Note You can always display the value of a global variable.

Printing Values of Properties


You can evaluate any valid expression in the Imrnediate window, including ex pressions
involving properties. The currently executing form or module determines scope. If execution
halts within code attached to a form, you can refer to properties of that form (or one of its
controls) and rnake the reference to the form implicit (you don't have to type it):
? BackColor
? Textl. Hei ght

Ass ume that Textl is a control on the currently executing forrn. The first statement prints to
the Immediate window the numeric value of the current forrn's background color. The
second statement prints the height of Text 1.
If execution is suspended in a module, you must explicitly specify a form:
? Forml.BackColor
? Forml.Textl.Height

Assigning Values to Variables and Properties


As you develop hypotheses about the cause of an error, you may want to test the effects of
particular data values. When in break mode, you can use assignment statements to set
values:
BackColor = 255
VScrolll . Valu e 100
MaxRows = 50

Microsoft Visua l Basic Programmer's Guide


238 Part 3 Applicatio n- Bu ildin g Techniques

The first two statements above alter properties of the currently executing form. The third
statement assigns a value to a variable. If execution was stopped in a module (or if you want
to refer to properties or controls of a different form) , it's necessary to refer to a form
explicitly, as described in the previous section.
After you set the values of one or more properties and variables, you can continue execution
to see th e res ults. Or, you can test the effect on procedures, as described in the next section.

Testing Procedures.
The Imrnediate window evaluates any valid Visual Basic executable statement. This window
won ' t accept data declarations, but you can enter calls to Sub and Function procedures.
Therefore, you can test the possible effect of a procedure with any given set of arguments by
entering a statement in the lmrnediate window just as you would enter it into the Code
window . For exa mple:
X - Ouadratic (2. 8. 8)
DisplayGraph 50, Arrl
Form_ MouseDown 1, 0. 100. 100

Visual Basic responds by switching to run time long enough to execute the statement, then
retums to break mode. At that point, you can see results and test any possible effects on
variables or property values.
Scope appli es to procedure calls just as it does to variables. You can call any procedure
within the curren tl y executing form . You can always calla procedure in a module.

Note Although al! executable statements are supported in the Irnmediate window , a control
structure is val id only if it can be completely expressed on one line. Thus, the following For
loop is va lid in the Immediate window :
For I = 1 To 20 : Print 2 * I : Next I

Tips on Using the lmmediate Window


Here are so rne shortcuts you can use in the Irnmediate window:
• Once yo u entera statement in the Immediate window, you can execute it again by
movin g the in sertion point back to that statement, then pressing ENTER anywhere on th e
line.
• Befare pressing ENTER you can edit the statement you're on to alter its effects .
• Use the mouse or the arrow key s to move around in the Immediate window. Don ' t press
ENTER unless yo u are at a statement you want to execute.
• You also ca n use the PAGE UP and PAGE DOWN keys to move a page ata time. CTRL+PAGE
DOWN alw ays takes you to the end of the Immediate window, which is past ali of the old
staterne nt s.
• The HOME ancl EN D keys move to the beginning and e nd of the current line.

Microsoft Visual Basic Programmer's Guide


Chapter 16 Debugging 239

When you move the insertion point back to a Print staternent (or staternent with a question
mark), bear in rnind that Visual Basic overwrites old staternents in the Irnrnediate window as
it prints each line of output. This rneans that unless you append a sernicolon (;) to the end of
the Print statement, it overwrites two staternents. For exarnple, suppose you rnove the
insertion point to the first of the three lines below:
? X
55
? Y* 20

Pressing ENTER prints the current value of X on the second line and then places the insertion
point at the beginning of the third line. The third line also is cleared. To avoid erasing the
third line, append a sernicolon to the first line:
? X
55
? Y* 20

For more information on the Irnrnediate window:

m Search Help for:


immediate

Special Considerations in Debugging Events


When prograrnrning for a graphical user interface environrnent, bear in rnind the status and
possible effects of events. It's important to be aware of what can happen while debugging.

Breaking Execution During MouseDown


If you break execution during a MouseDown event procedure, you rnight release the mouse
button or use the mouse to do any number of tasks. The problem is that when you continue
execution, the application ass umes that the mouse button is still pressed down. You don't get
a MouseUp event until you press the mouse button down again and then release it.
However, when you press the rnouse button down during run rnode, you ' ll once again break
execution in the MouseDown event procedure, assurning you have a breakpoint there.
Consequently, you ' ll never get to the MouseUp event. The solution is usually to rernove the
breakpoint in th e l\llouseDown procedure.

Breaking Execution During KeyDown


If you break execution during a KeyDown procedure, similar considerations apply : If you
retain a breakpoint in a KeyDown procedure, you rnay never get a KeyUp event. (KeyDown
and KeyUp are _described in Chapter 18, "Interacting with the Environment.")
If you remain aware of how break mode can put events at odds with what your application
expects, you can usually find solutions. As suggested above, you may have to remove
breakpoints. You also may need to change the values of variables that depend on the
sequence of events.

Microsoft Visual Basic Programmer's Guide


240 Part 3 Application-Building Techniques

Testing and Using Command-Line Arguments


Once you complete your application and produce an executable file, your users will be able
to specify command-line arguments. These arguments provide data to your application at
startup. The user can enter them by choosing the operating environment's Run command
and then typing arguments after the application name.
Command-line arguments also can be specified when starting an application with the Shell
command.
For exan1ple, suppose you created an alarm clock application. One of the techniques for
setting the alarm time is to Jet the user type in the desired time directly . The user might en ter
the following string in the Run command dialog box:
Alarm 11:00:00

The Command$ function (intrinsic to Visual Basic) retums all arguments entered after the
application name (in this case, Alarrn). The Alarm application has just one argument, so in
the application code, you can assign this argument directly to the string that stores the time
to watch for:
AlarmTime - Command$

If Command$ retums an empty string, there are no command-line arguments. The


application must prompt for the information directly or select sorne default action.
To test code that uses Command$, you can specify sample command-line arguments from
within the Visual Basic environment. The application evaluates this sampl e command-line
input the same way it would if the user had typed these on the command line.

To set sample command-line arguments:


1 From the Run menu , choose Modify Command$.
2 Enter the sample arguments. (Do not type the name of the application itself.)
3 Click OK or press ENTER .

3 Run the application .

For more information on the Command$ function, see the Language Reference , or:

íf:íll Search Help far :


- Command$

Microsoft Visual Basic Programmer's Guide


So far, you ' ve seen only the beginning of what a Visual Basic application
can do. A substantial application involves many forms, modules, and
procedures. Furthermore, sorne applications d_o advanced system-level work,
,Tr,
such as storing information in di sk fil es, calling dynamic-link libraries , or
communicating with other applications.
Although sorne of the advanced work is not difficult, you need a good grasp
of the techniques presented in the first three parts of this book befare forging
ahead. Once you understand those techniques, the next few chapters can
show you how to do even more with the advanced features in Visual Basic .

••••
••••
Advanced Language Features

Chapter 9, "Language Elements," presented enough information to help you understand the
application-building techniques discussed in Part 3 and to write sorne useful applications.
But Visual Basic has a number of refined features designed to meet special needs. As you
write larger applications, you'll find that sorne of these features are very helpful.
If you have experience in Microsoft QuickBasic or the Basic Professional Development

+ System, most of the features presented here are already familiar to you. Note, however, that
they are not precisely the same in every case. You should read carefully before you assume
that Visual Basic works justas other Basic products do.
The main sections in this chapter are:



Controlling Execution
Data Declaration
Arrays
-
• The Global Module
• Type and Constant Definitions
244 Part 4 Advanced Appl ications

Controlling Execution
The next three sections describe how to place control structures inside other control
structures and how to use different versions of the Exit statement. A control structure inside
another control structure is said to be nested.

Nested Control Structures


As is the case with Microsoft QuickBasic and a number of other languages, the control
structures in Visual Basic can be nested to any leve!. Nesting is a way of representing
complex logic or decisions in a readable form in decision structures and loop structures.
For example, the following code uses nested If statements to combine different conditions
when deciding on an action :
If BabyCheckBox.Value = 1 Then
If Dog.Value Then
Display.Text - "puppy"
Elself Cat.Value Then
Display.Text - " kitty"
End If
El se
If Dog.Value Then
Display.Te xt - "d og"
Elself Cat.V alue Then
Display.Text - "cat"
End I f
End I f

Nested control structures work in a similar fashion. Especially comrnon are nested For
loops, which handle arrays of strings and multidimensional arrays. For example, the
following code prints tables of multiples for numbers from 1 to 20:
Dim I As Integer, J As Integer
Far I - 1 To 20
Print "Multip les of "; I·
Far J - 1 To 10
Print Chr$(9) ; l*J;
Next J
Print
Next I

The I loop is the outer loop ; for each increment of I , J run s an entire cycle from 1 to 1O.
Note that each Next statement applies to the nearest For statement. Thus, the first Next
terminates the I loop, and the second terminates the J loop.
The previous two examples show nested If statements and nested For loops. But you are not
limited to nesting a control structure inside another of the sa me type. You can nest contro l
structures to any level and in any combination .

Microsoft Visual Basic Programmer's Guide


Chapter 17 Advanced Language Features 245

Exiting a Control Structure


The Exit statement enables you to exit directly from a For loop, Do loop, Sub procedure, or
Function procedure. Syntactically, the Exit statement is simple: Exit For can appear as
many times as needed inside a For loop, and Exit Do can appear as many times as needed
inside a Do loop:
For counter = start To end [Step increment]
[statementblock]
[Exit For]
[statementblock]
Next [counter [, counter]]

Do [{While IUntil } condition]


[statementblock]
[Exit Do]
[statementblock]
Loop

The Exit Do statement works with ali versions of the Do loop syntax. An important
difference between Do While ... Loop and the While ... Wend statement is there is no way to
exit directly from While ... Wend.
Exit For and Exit Do are useful because sometimes it's appropriate to quita loop
immediately, without performing any further iterations or statements within the loop. For
example, suppose you want to test a number to see if it is a prime number. (A prime number
is an integer that is only divisible by itself and the number 1.) The pseudocode for a prime-
number test on a number N might be:
Ass ume Ni s prime
Determine square root of number N
For each number from 2 to square root of N
If number evenly divides N
Ni s not prime
Stop te s ting numbers

A first attempt to write a prime-number Function procedure might look like this:
Function Prime (N As Integer) As Integer
Const TRUE - - 1. FALSE= 0
Dim R As Integer, I As Integer

Prime= TRUE
R - Sqr(N)
For I = 2 To R
If N Mod I = 0 Then
Prime= FALSE
End If
Nex t I
End Fun cti on

Microsoft Visual Basic Programmer's Guide


246 Part 4 Advanced Applications

This procedure produces correct results, but it's inefficient; it doesn' t stop testing numbers
when a divisor of N is found. Once it's determined that Ni s nota prime number, it's no
longer necessary to continue the For loop. Therefore, a more efficient version uses Exit For
to termínate the loop once it is deterrnined that N is not prime. The statements are the same
except for the For loop:
Far I - 2 To R
If N Mod I = 0 Th en
Prime - FALSE
Exit For
End I f
Next I

Note that the Exit statement almost always appears inside an lf state ment or Select Case
statement nested inside the loop.

Exiting a Sub or Function Procedure


The syntax of Exit Sub and Exit Function is similar to that of Exit For and Exit Do in the
previous section. Exit Sub can appear as many times as needed, anywhere within the body
of a Sub procedure. Exit Function can appear as many times as needed, anywhere within
the body of a Function procedure.
Exit Sub and Exit Function are useful when the procedure clearly has done everything it
needs to do and can retum immediately. For example, the prime-number example of the last
section can be written with an Exit Function statement rath er th an Exit For. In this case,
the effect is the same:
Function Prime (N As Integer) As Integer
Co nst TRUE = - 1. FALSE - 0
Di m R As Integer, I As In teger

Prime= TRUE
R = Sqr(N)
For I = 2 To R
If N Mod I 0 Then
Prime - FAL SE
Ex i t Function
End I f
Next I
End Fun ction

Microsoft Visual Basic Programmer's Guide


Chapter 17 Advanced Language Features 247

Data Declaration
You can declare Static variables when you want procedures to have persistent data, and you
also can declare data using the following special types: Form, Control , and fixed-length
strings. The next several sections describe these advanced techniques.

Static Variables
Normally, when a procedure is finished, the values of its local variables are lost. The next
time the procedure is executed, all local variables start at zero oran empty string.
You can make Visual Basic preserve the value of a local variable by making it static. Use
the Static keyword to declare one or more variables inside a procedure, exactly as you
would with the Dim statement:
Static X As Oouble, Y As Double
Static Counter As Integer

For example, the following Click procedure changes the background color back and forth
between two values. The procedure must remember the previous state it was in, and uses a
static variable, Fl a g, for this purpose:
Sub Form_Click ()
Static Flag As Integer
If Flag - 0 Then
BackColor - RGB (255, 0, 0)
Flag - 1
El se
BackColor = RGB (0, 128, 128)
Flag= 0
End If
End Sub

Yo u also can produce the same result by declaring Fl a g in the Declara ti o ns section of the
form, making it into a form-level variable. However, once you change the scope of a
variable this way , the procedure no longer has exclusive access to it.

Declaring Ali Local Variables As Static


To make all local variables in a procedure static by default, place the Static keyword at the
beginning of a procedure heading. For example:
Static Sub Ouad (A%, 8%, C%) As Double

This causes all the local arguments in the procedure to be considered static, regardless of
whether they are declared with Static, Dim , or declared implicitly. Each time the procedure
is called, it remembers the values of the local variables from the last time the procedure ran.
You can place Static in front of any Sub or Function procedure headin g; this includes both
event proced ures and general procedures.

Microsoft Visual Basic Programmer's Guide


248 Part 4 Advanced Appl ications

Arguments Declared As Form


The spec ial Form data type can be used to declare an ítem in an argument list. Using a
Form argument enables you to write generalized procedures that operate on any number of
different forms. Only arguments can be declared As Form; variables of this type are not
val id .
The Control data type is similar and is described in the next section.
Suppose you want to perform the same color initializations for all the forms you work with.
Without the Form type , yo u mu st repeat a similar gro up of statements for each form:
Forml.BackColor RGB(0, 0, 128)
Forml.ForeColor RGB(l92, 0, 0)
Forml.Dra wColor = RGB(255, 255, 255)

Fo rm 2.BackColor RGB(0, 0, 128)


Form2.ForeCo l or - RGB(l92, 0, 0)
Form2.Dra wCo l or = RGB(255, 255, 255)

Form3.BackColor = RGB(0, 0, 128)


Form3.ForeColor RGB(l92, 0, 0)
Form3.Dra wColor = RGB(255, 255, 255)

By includin g an argument of type Form, you can write a procedure that assigns these colors
for any form:
Sub SetColor s (ThisForm As Form)
This Form.BackColor RGB(0 , 0, 128)
ThisFo rm.F or eColo r RGB(l92, 0, 0)
ThisF orm.Draw Colo r RGB(255, 255, 255)
End Sub

You then ca n call the procedure and pass the name of any form yo u wish as an argument:
Se t Colors Forml
SetC olors Form2
Se t Colors Form3

Form and Control variables have two important res trictions that do not apply to other types:
• You ca n use them onl y in arg ument lists, not in other kinds of variable declarations.
• You ca nnot assign va lues directly to Form or Control arg uments at any time. Yo u can ,
however, assign values to their properties.

Arguments Declared As Control


The Control keyword is used in much the same way as Form . A procedure that has an
arg ument declared As Control can operate on any number of different contro ls passed as
arg umen ts.

Microsoft Visual Basic Programmer's Guide


Chapter 17 Advanced Language Feature s 249

Chapter 14, "Responding to Mouse Events," introduced As Control in the context of


DragDrop and Dragüver events. These events pass Source (the source control being
dragged) asan argument. You can use that argument by referring to its properties.
You also can use As Control declarations in general procedures. For example, the following
procedure altemately hides and reveals any control passed to it by reversing the setting of
th e Vi sible property:
Sub Cl oak (T hi sCo ntrol As Control)
ThisControl.Visible = Not ThisControl.Visible
End Sub

You can use this procedure with any number of different controls (except timers, which have
no Visible property):
Cloak Te xtl
Cloak Text2
Cloak Pi cture l

Using a Control argument requires extra care, since different types of controls support
different sets of properties. Visual Basic generates a run-time error if you access a
nonexistent property of a Control argument.
For example, the followin g fragment works correctly for text boxes, because text boxes have
a Text property:
Sub InitBox (TextBoxCont r ol As Control)

Tex tB oxC ontrol . Text = "H el lo, ther e . "

Therefore, you can pass a text box to thi s proced ure without getting an error:
InitBo x Tex tl

But the following statement causes a run-time error, assumi ng Commandl is a command
button . This statement passes the command button as an argument to InitBox, whi ch then
refers to the Text property. Because command buttons don ' t have a Text property, Vi sual
Basic generates an error:
InitB ox Commandl

To ensure that this error does not happen, you may want to test the type of the co ntrol by
using the Typeüf keyword , as described in the next section .

Determining Type of a Control Argument


To determine the exact type of a Control argument, you can use an If... Typeüf or
Elself ... Typeüf state ment, which has thi s sy ntax:
{ If I Elself } Typeüf control Is controltype Then

Microsoft Visual Basic Programmer's Guide


250 Part 4 Advanced Applications

The TypeOf and Is keywords appear only in exactly that form of syntax. You can test for
only one control type ata time, and you cannot combine that syntax with other conditions on
the same line. However, an lf Typeüf or Elself TypeOf statement can be part of a larger If
block that tests for other conditions . For example:
If X= 3 Then
Print X
Elseif Typeüf ThisControl Is Timer Then
Thi sControl. Interval ~ 1000
End I f

The control is an argument declared As Control. The controltype is one of the following
keywords:
CheckBox Frame PictureBox
ComboBox HScrollBar TextBox
CommandButton Label Timer
DirListBox ListBox VScrollBar
DriveListBox Menu
FileListBox OptionButton

For example, the following fragment places a string in a control if the control is a text box :
Sub InitMyControl (Sou rce As Control)

lf TypeOf Source Is TextBox Then


Source.Text = "Welcome"
End I f

Sometimes you may want to take an action if a control is not a particular type. Although you
can' t combine the Not keyword with Typeüf, you can produce the same effect by including
an empty statement block combined with an Else clause. For example, the following code
sets the Visible property to O if ThisControl is not a timer:
lf TypeOf ThisControl Is Timer Then
Else
ThisControl.Visible = 0
End If

Microsoft Visual Basic Programmer's Guide


Chapter 17 Advanced Language Features 251

Altematively, you can simply exit the procedure if a timer is detected:


If Typeüf ThisControl Is Timer Then Exit Sub
ThisContról . Visible = 0

Fixed-Length Strings
By default, a string variable or argument is a variable-length string; the string grows or
shrinks as you assign new data to it. Y ou also can declare strings that always have a set
length. Y ou specify a fixed-length type wi th this syntax:
String * size

Fixed-length strings are use ful in random-access file operations (as explained in Chapter 21,
"Processing Files"). Or, suppose you want to print a report and you want a string to always
take up the same amount of space. For example, this statement declares EmpName as a fixed-
length string of 30 characters:
Dim EmpName As String * 30

If you assign a string of fewer then 30 characters, EmpN ame is left-justified and padded with
trailing spaces.
You can freely altemate between fixed-length and variable-length strings. If you assign a
string that is too long for the fixed- length string, it simply truncates the characters. For
example:
Dim String5 As String * 5, Mammal As String

Mammal = "El ephant"


Print Mammal

String5 = Mammal
Print String5

The code produces this output on the form :


Elep hant
Eleph

Because fixed-length strings are often padded with trailing spaces, you may find the intrinsic
RTrim$ function useful when working with them. For more information on RTrim$ , see
the Language Reference, or:

m Search Help for:


RTrim$

Microsoft Visual Basic Programmer's Guide


252 Part 4 Advanced Applicati ons

Arrays
If you have programmed in other languages, you ' re probably familiar with the concept of
arrays. Arrays enable you to refer to a series of variables by the same name, and use a
number (an index) to tell them apart. This helps you create smaller and simpler code in many
situati ons, because you can set up loops that deal efficiently with any number of cases by
using the index number.
In additi on, Visual Basic introduces a new kind of array - the control array. A control array
has special features and does not follow all the rules of standard arrays. The differences are
explained below.

lmportant Although co ntrol arrays are similar to other kinds of arrays, they differ in a number of
details . What Visual Basic documentation says about arrays generall y does not apply to
control arrays, unless specifically stated.

Control Arrays
Visual Basic requires the use of control arrays in two situations:
• Writing code far menus that grow or shrink
• Creating new co ntrols at run time

Chapter 1O, "Responding to Commands," and Chapter 13, "Creating Graphical Effects,"
introduced co ntro l arrays and explained their use far these purposes.
However, you ca n use control arrays at other times. Even thou gh it may have man y
elements. the entire control array has only one event procedure far eac h type of even t (Click,
KeyPress, and so on). Creating a control array makes sense when a number of controls can
benefi t from sharing most of their code.
Control arrays do preserve sorne flexibility. Whenever any control in the array recogni zes an
event, Visual Basic passes the indexas an extra argument. This argume nt always comes
befare any other arguments that may be passed. For example:
Sub MyCtlArray_ KeyPress (Index As Integer, KeyAscii As Integer)

Once inside the event procedure, yo u can use lndex to determine which control actually
received the event. An element of a control array can be referred to as:
arrayname (/ndex)

Thus, MyCtlArray(0) and MyCtrlArray(l) refer to specific elements in a contro l arra y, and
can be used anywhere ordinary control names are used.

Microsoft Visual Basic Progra mmer's Guide


Chapter 17 Advanced Language Features 253

Control arrays differ from ordinary arrays in the following ways:


• They are not declared in code.
• They are limited to one dimension.
• They do not have definite upper bounds, and you don't have to use sequential index
numbers.

Y ou create a control array at design time, either by assigning two controls the same name
(CtlName property), or by assigning a value to a control's Index property. The latter
technique produces a control array of just one element. This is useful when you want to
create controls at run time, but don't want to start with a lot of controls.
Control arrays are limited to one dimension. Visually, you can create a grid of controls, but
within the code, each control is identified by a single number.
The lower bound of any control array is zero, and index numbers can run as high as the
system resources allow. Unlike ordinary arrays, you can skip index numbers. MyCtlArray(l)
and MyCtrlArray(9) may both correspond to controls, even though there are no controls with
index numbers from 2 to 8. When you first create a control array, Visual Basic assigns
default index numbers, starting at O and increasing by increments of 1 as each new control is
added to the array. You then can change indexes by resetting each control's Index property .
Note that indexes can be reassigned only at design time.

Note Another lirnitation on control arrays is that, unlike a standard array, a control array
cannot be passed as a single argument. Each element of the control array must be passed as a
separate argument.

Arrays of Variables
Like other languages, Visual Basic enables you to define arrays of standard data types. An
array is a series of memory locations that share the same name and are identified by an index
number. Unlike control arrays, standard arrays have both upper and lower bounds, and there
are no empty elements. Visual Basic allocates space for each index number, so don't declare
an array larger than you need it to be.
Visual Basic has three important rules regarding ordinary (fixed) arrays:
• In the global module, use the Global statement to declare array_s.
• At the form or module leve!, use the Dim statement to declare arrays.
• Within a procedure, use the Static statement (although you can use Dim if the whole
procedure is declared Static). For more inf~rmation, see "Static Variables" earlier in this
chapter.

The rules change when you create a dynamic (variable-length) array. The section "Dynamic
Arrays" later in this chapter discusses these rules.

Microsoft Visual Basic Programmer's Guide


254 Part 4 Advanced Applications

When declaring an array, follow the array name by parentheses and the upper bound. The
upper bound must be an integer. For example, these array declarations can appear in the
Declarations section of a form or module:
Oim Cou nter s (14) As Integer
Dim Sums (20) As Oouble

In the global module, you simply use Global in place of Dim . The same declarations within
a procedure use Static :
Static Cou nter s (14) As Integer
Stat i c Sums (20) As String

The first declaration creates an array with 15 members, with index numbers running from O
to 14. The second creates an array with 21 members, with index numbers running from O to
20. The default lower bound is O. However, you can change the default lower bound to l by
placing an Option Base statement in the Declarations section of a form or module:
Option Base 1

For more information on the Option Base statement, see the Language Reference, or:

m Search Help for:


Option Base

Another way to specify lower bounds is to use the To keyword (a lower bound also must be
an integer):
Dim Counters (1 To 15) As Integer
Oim Sums (1 00 To 120) As String

ln the declarations above, the index numbers of Counters run from 1 to 15 , and the index
numbers of Sums run from 100 to 120.

Note Other versions of Basic permit implicit declaration of arrays; Visual Basic <loes not.
You must declare an arra y before using it.

Arrays are an efficient way to handle many array elements in a loop. Each element is
accessed through a combination of the array name and index. For example, if the lower
bound of array Counters is 1, then the third element of the element is :
Counters(3)

The follow ing loop initializes all elements in the array to 5:


Static Counters (1 To 15) As Integer
Oim I As Integer
Far I = 1 To 15
Co unter s (!) = 5
Next

Microsoft Visual Basic Programmer's Guide


Chapter 17 Advanced Language Features 255

Two-Dimensional Arrays
Sometimes information is naturally represented in a grid, or matrix - a data structure that
has both rows and columns. You can declare two-dimensional arrays that reflect the
structure of a grid. For example, the following statement declares a 10-by-10 array within a
procedure:
Static MatrixA (9 , 9) As Double

Either or both dimensions can be declared with explicit lower bounds:


Sta tic MatrixA (1 To 10, 1 To 10) As Double

Once you declare a two-dimensional array, you can efficiently process it by using nested
For loops. For example, these statements initialize every element in Má tri xA to 1:
Dim I As Integer, J As Integer
Sta tic MatrixA (1 To 10, 1 To 10) As Double
For I = 1 to 10
For J - 1 To 10
MatrixA(I, J) = 1
Next J
Next I

Multidimensional Arrays
With Visual Basic, you can declare arrays of up to 60 dimensions. Each dimension is
declared by giving an upper bound and optionally a lower bound . For example:
Dim MultiD (3, 1 To 10, 1 To 15)

This declaration creates an array that has the dimensions 4 by 10 by 15. The total number of
elements is the product of these three dimensions, or 600.

Note When you start adding dimensions toan array, the total storage needed by the array
increases dramatically, so be careful in the use of multidimensional arrays.

Generally, multidimensional arrays are useful for highly specialized mathematics and
science applications (although three-dimensional arrays are useful in projected graphics) .
Most applications rarely require arrays of more than two dimensions.

Dynamic Arrays
Sometimes, you may not know exactly how lar.ge to make an array. You may want to have
the capability of changing the size of the array at run time.
A dynamic array can be resized at any time. Dynamic arrays are among the most flexible
and convenient features in Visual Basic, and they help you to manage memory efficiently.
For example, you can use a large array for a short time, then free up memory to the system
when yo u' re no longer using the array.

Microsoft Visual Basic Programmer's Guide


256 Part 4 Advanced Applications

The alternative is to declare an arra y with the largest size possible, and then just ignore arra y
eleme nt s you don 't need. However, this approach wastes storage and, if used often, might
even cause your application to run low on memory .

To create a dynamic array:


1 Declare the array with a Dim statement (or Global, if the declaration is in the global
module) andan empty dimension list. Far example:
Oim OynArray ()

2 Allocate the actual number of elements with a ReDim statement.

The ReDim statement can appear only in a procedure. Unlike the Dim and Static statement,
ReDim is an exec utable statement - it makes the application carry out an action ar run time.
The ReDim statement supports the same syntax described in the Jast few sec tions far fixed
arrays. Each use of ReDim can change the number of elements, and lower and upper bounds
far each dimension. However, the number of dimensions must not change.

important Each tim e you execute the ReDim statement, all the values currently stored in the array are
lost. Visual Basic resets the values to zero-or, in the case of strings, to the empty string.

Far examp le . the dynamic arra y Ma tri x 1 is created by first declaring it at the farm leve!:
Dim Matrixl () As Integer

A procedure then allocates space far the array:


Sub Ca l cValuesNow ()

ReDim Matrixl (19. 29)

The ReDim statement allocates a matrix of 20 by 30 integers (at a total size of 600
elements) . Alternatively, the bounds of a dynamic array can be se t using variables:
ReDim Matrixl (X. Y)

When you create a dynamic array that is local to a procedure, th e first step above
(declaration with Dim at the beginning of the procedure) is recommended but not req uired.
Declaring a dynamic array first with Dim limits the number of dimension s to 8. lf" you need
more dimensions, avoid using Dim and create the array directly with ReDim :
ReDim BigArr (A. B. C. D, E. F. G. H. I) As Integer

Note Thi s techn ique supports the normal limit on the number of dimensions (60) .

11/ficrosoft Visual Basic Programmer's Guide


Chapter 17 Advanced Languag e Feature s 257

The Global Module


The global module contains vari able declarations, constant definitions, and type information
that is recognized by the entire application. Thi s section lists:
• What to include in the global module
• What statements are supported only in the global module
• What syntax changes are necessary when you transfer a statement to the global module

Each project has exactly one global modul e, although you may find that you don ' t use it for
simple applications with a single form. Yet even for small projects, the global module is
con venient if you include any constant defi nitions from the CONSTANT.TXT fil e. These
definiti ons are written using the Global keyword, so they must be placed in the global
module or else rewritten.
Unlike other modules, the global module cannot include any procedures. The global module
is like one large Declarations secti on; it has no definite subdivisions.
The global module can include:
• Global variable declarations.
• Deftype statements. These statements, introduced later in this chapter, determine the
default type of variables. When placed in the global module, Deftype statements affect
only the data type of global variables.
• Global constant definitions.
• User-defined type statements. These are similar to structures or records in other
languages .

Type . .. End Type , whi ch crea tes a user-defi ned type, can be pl aced onl y in the global
module. Once created, a user-defi ned type can declare a vari able at any leve!. The section
"User-Defin ed Types" at the end of this chapter describes how to create and use these types .
In contras t, variable declarati ons and constant definition s can be placed in form s, modul es,
and procedures, but are not global in scope when placed at those levels.
Variabl e declarati ons and constant definiti ons use a different syntax at the global leve]:
• In variable declarati ons, the Dim keyword is repl aced by Global.
• In constant dec larati ons, Global must precede Const.

The fo ll owing examples show a variab le and constant decl arati on at the modul e leve], and
the sa me statements rewri tten so they ca n be 1:1 sed in the global modul e.
Form-level statements Rewritten for the Global module
Dim Salary As Currency Global Sal a ry As Curre ncy
Di m X Gl obal X
Co ns t FAL SE 0 Glo bal Co nst FAL SE 0

Microsoft Visual Basic Programmer's Guide


258 Part 4 Advanced Applications

Type and Constant Definitions


The statements described in this section - symbolic constants, the default data type, and
user-defined types -are nonexecutable statements that can make your code more readable,
structured, and easier to maintain .

Symbolic Constants
Often, you ' ll find your code is sprinkled with constant values that appear over and over. Or
you may find that your code depends on certain numbers that are difficult to remember, and
(in and of themselves) , have no obvious-meaning unless you look up their significance.
Man y such numbers are recorded in CONST ANT.TXT.
In these cases you can greatly improve the readability of your code and make it easier to
maintain by using the Const statement. This statement enables you to use a meaningful
name, called a symbolic constant, in place of a number. In sorne respects, a constant
definition is like a variable. But unlike a variable, the value of a constant cannot change
during program execution .
A Const statement has scope just as a variable declaration does, and the same rules apply. If
you want to make sure a constant definition is recognized throughout the application, place it
in the global module and put the keyword Global before Const.
The syntax for a Const statement is:
[Global] Const constantname =expression [, constantname = expression ] ...

The argument constantname is a valid sy mbolic name (the rules are the same as the rules for
creating variabl e names), and expression is made of numeri c or string constants.
A Const state ment can represe nt a mathematical qu antity:
Co nst PI = 3 .1 4159265
Co nst SQROOT2 = 1.41421356
Co nst E= 2.71828 183

TRUE and FALS E constants are useful wherever you need to set a Boolean ·property :
Co nst TR UE = - 1 , FAL SE = 0

Once you define co nstants, you can place them in your code to make it much more readable.
For exa mpl e:
Che c kBox . Va lu e = TRUE
Angle = PI
Angl e2 = PI / 2

The ex pression on the ri ght side of the equal sign (=) is ofte n a number, but also can be an
ex press ion that produces a num e ric or string result (although it cannot contain call s to
fun cti ons) . You ca n even defin e constants in term s of previously defined constants:
Con s t PI 2 = PI * 2

Mic roso ft Visual Basic Programmer's Guide


Chapter 17 Advanced Language Features 259

The Const statement also can be used to defi ne string constants:


Const VERSION = "0 7 .10. A"
Const RELEASE _ DATE = "Apri l 17, 1992"

The Default Type


If you declare a variable without usi ng either a type-declaration character oran As clause,
Visual Basic assigns that variable the default data type. The default type is normally single-
precision floating point. However, you can use a Deftype statement to specify a different
default type far any given farm or module.
Deftype statements specify the default type far variables according to the first letter of the
name. The Deftype statement affects all variable declarations that fallow it. Note that in
variable names, Vi sual Basic makes no real di stinction between uppercase and lowercase
letters, so Defl nt A- E has the same effect as Defl nt a - e .
For example, the fallowing statements declare a series of variables as integers. First, the
Deflnt statement declares all variabl es that start with the letter X or Y to be integers. Then,
the Dim statement actually declares the variables:
Defln t X, Y
Dim XGr i d, YGrid, Xl , Yl , X2, Y2

Deflnt is a Deftyp e statement; without this statement in the example above, you'd have to
add an As Integer clause to each of the variables in the list.
A Deftype statement can be placed in the global module, or in the Declarations section of a
farm or module. The statement affec ts the default type of all variables in that farm or
module. Thus, Deftype statements in the global module determine the default type far global
variables, but have no effect on other variab les. Deftyp e statements in a farm affect farm-
level variables as well as local vari ab les in procedures attached to that farm . It' s the same far
modules .
Vi sual Basic supports six different kinds of Deftype statements, one far each data type.
Statement Associated data type
Deflnt letterrange Integer
DefLng lette rrange Long
DefSng letterrange Single
DefDbl letterrange Double
DefCur letterrange Currency
DefStr lette rrange String

With each statement, lette rrange is either a single letter ora range of letters described by this
syntax :
letterl [-letter2 ]

Microsoft Visual Basic Programmer's Guide


260 Part 4 Advan ced Appli catio ns

You also can specify a combination of ranges, separated by commas. Thus, the followin g are
all valid state ments:
' Declarations
Deflnt A- E, I - M, T
Deflng F
DefDbl X- Z

The range A-Z is a special case. Thi s range, and only thi s range, causes the default-type
range to include ali international characters as well as the letters in the English alphabet.

User-Defined Types (Structures)


With the Type statement in Visual Basic, you can build new data types made up of the
standard rypes. Once a type is defined, yo u can declare variables to be of this type. For
example, once the type ComplexNum is defined, you can declare a variable or argument to
be As ComplexNum in any Dim, Static, or Global statement, or in an argument list.
User-defined types are si mil ar to C structures and Pascal records; they maintain related
information (such as an employee record) in a single data structure.

lmportant You can place Type definitions only in th e global module. The Type statement is not valid
anywhere else .

The Type statement uses th is sy ntax:


Type usertype
elementname As rypename
e/ementname As typename

End Type

In thi s syntax displ ay, usertype is the name yo u c hoose for the new type. Each elementname
specifies a field of data within the user-defi ned type. The elementname fo llows the same
rules of Visual Basic vari ab le names, and eac h elementname has a corresponding typename .
The typename indicates what kind of data is stored in that field. This type can include any of
the standard data types, including variable-length strings. The type also can be another user-
defi ned type that has been previously defined.

Note Other versions of Basic require that strin gs in user-defined types be fixed-length
strings . Vis ual Bas ic supports vari able-length strings (the standard condition of strings) in
user-defined types . However, Visual Basic doesn' t support arrays inside user-defi ned types .

Microsoft Visual Basic Programmer's Guide


Chapter 17 Advanced Language Fe atures 261

The following user-defined type includes a double-precision floating-point number and two
variable-length strings. Note that fixed-length strings should be used if the type is intended
for random-access file operations:
Type StateData
Gov As String * 30
StateBird As String * 20
PerCapincome As Double
End Type

Once a user-defined type is declared in the global module, you can use the name of the type
as part of a variable declaration, just as you would with any of the standard types:
Dim I As Integer
Oim California As StateData
Dim USA (1 To 50) As St ateData

In the statements, Cal i fo r ni a is an instance of StateData, just as I is an instance of


Integer. StateData names a general type, and has no direct purpose in a program except to
declare variables. Cal i fo r ni a is an actual variable and can hold data.
To access individual fields of Cal i fo r ni a, use the point (.) notation:
variable .elementname

Far example, the following statement places the name "Cary Grant" in the Gov field:
California.Gov = "Cary Grant"

Microsoft Visual Basic Programmer's Guide


lnteracting with the Environment

Microsoft Windows and Presentation Manager provide access to a number of special system
resources, including the Clipboard, system time, idle-loop processing, and low-level
keyboard handling. By taking advantage of these features, you can give your applications the
extra flexibility that polished, professional applications often require.

For example, although the techniques in Chapter 1O, "Responding to Commands," cover the
most typical use of the keyboard, only the low-level keyboard handling in this chapter gives
,n, you complete access to the keyboard - including the arrow keys and the numeric keypad.
Visual Basic supports simple, direct hooks into a number of operating environment
resources. As this chapter demonstrates, it' s possible to create a useful digital clock
application with only one line of code. Small enhancements can then tum the application
into an alarm clock or give it other custom features .
The main sections in this chapter are:
• Working with Selected Text
• U sing the Clip board Object
• Using Timer Controls
• Writing Idle Loops with DoEvents
• Writing Low-Leve.l Keyboard Handlers

••••--
--
--
-
264 Part 4 Adv anc ed Appl ic ations

Working with Selected Text


Text boxes a nd co mbo boxes have a seri es of p roperti es fo r selected tex t that are espec iall y
handy w he n working w ith the C li pboard, as you ' 11 see in the nex t section. These properti es
re fer to the bl ock of text selec ted (h igh li ghted) inside the co nt rol. T hey e na ble you to create
cut-and-pas te functions fo r the user. T he fo ll ow in g properties can ali be ch anged at run tim e .
Pro-perty Description
Se!Start A long integer that spec ifies the starting pos iti on of the selected
bl ock of text. If no text is selec ted , thi s property spec ifi es the
positi on of the inserti on poi nt. A se tting of O indi cates the p os iti on
just before the first c harac ter in the tex t box or combo box . A setting
egu a! to the le ngth of the text in the tex t box or combo box indi cates
the posi tio n ju sl after the last character in th e co ntro l.
Se lLength A long integer that specifies the nu mber of c harac ters selected.
Se!Text The string con taining the selected c harac ters (oran e mpty string, if
no c haracters are selected).

Yo u can actually control w hat tex t is se lected by setting the Se!Star t and SelLe ngth
properties. Far example, these statements hi ghli ght ali the tex t in a text box :
Textl.SelSta r t = 0 Start hig hlight befare f i rst c haracter.
Textl.Se ll ength = Len ( Textl .Text ) ' Highlight to end of text.

If yo u assign a new stri ng to Se lTex t. the new stri ng repl aces whatever text is se lected. T he
hi ghli ght is the n removed and th e in sertio n point is placed j ust after the e nd of the newly
in se rted text. Far example, the following statemenl replaces the se lected text with the string
'Tve just bee n inserted !":
Tex tl.SelText = " I've just been inserted !"

lf no tex t was selected , the string is simply pas ted in at the in se rt ion point.
Fa r more informati on on the Se!Start , Se!Length , and Se!Text properties, see the Language
Reference , o r:

m Search Help for:


te xt

Mic rosoft Visual Ba sic Programmer's Guide


Chapter 18 lnteracting with the Environment 265

Using the Clipboard Object


The Clipboard object is one of four special objects predefined in Visual Basic. (The other
three are Screen, Printer, and Debug). The Clipboard object has no properties or events, but
it has a series of methods that enable you to transfer data to and from the environment's
Clipboard.
Two of the most useful Clip board methods are SetText and GetText. These two methods
transfer string data to and from the Clipboard, as shown in Figure 18.1.

Abe!
SetText - - - - - - - . ~

~ - - - - - - ~ , . ----GetText
Abe! _...--
- -w
Textboxes Environment
Clipboard

Figure 18.1 Moving data to and from the Cl ipboard with SetText and GetText

SetText copies text onto the Clipboard, replacing whatever text wa·s stored there before. You
use SetText like a statement, and its syntax is:
Clipboard.SetText data$[, format o/o ]

GetText returns text stored on the Clipboard. You use it like a function :
destination = Clipboard.GetText ( )

By combining the SetText and GetText methods with the selection properties introduced in
the previous section, you can easi ly write Copy, Cut, and Paste commands for a text box .
The following procedures implement these commands for controls named CopyCmd,
CutCmd, and PasteCmd:
Sub CopyCmd_Click ()
Clipboard.SetText Textl . SelText
End Sub

Sub CutCmd_Click ()
Clipboard.SetText Textl . SelTe xt
Textl. SelText -
End Sub

Sub PasteCmd_Click ()
Textl.SelText - Clipboard.GetText()
End Sub

Microsoft Visual Basic Programmer's Guide


266 Part 4 Advanced Appl ications

Note The example works best if these controls are menu commands, because you can use
menus while Tex tl has the focus .

Let' s examine two of these statements. In the Copy command, the statement consists of two
components: the SetText method andan argument (Textl .SelText) passed to that method.
The statement tells Visual Basic to copy the tex t selected in Textl to the Clipboard:
Cl ipboard.SetTe xt Textl.SelText

In the Paste comrnand, the GetText method retums the string of text currently on the
Clipboard. An assignment statement then copies this string into the selected portian of the
text box (Text l. SelText). lf no text is currently selected, Visual Basic places this text at the
insertion point in the tex t box:
Textl.SelText - Clipboard .GetText( ,

This code assumes that ali text is transferred to and from the text box Textl. This may sound
li mited at first , but the user actually can copy, cut, and paste between Textl and controls on
other forrns. Because the Clipboard is shared by the entire environment, the user can transfer
text between Text 1 and any application that uses the Clipboard.
If you want the Copy, Cut, and Paste commands to work with any text box that has the
foc us, use the ActiveControl property of the Screen object. The following code provides a
reference to whichever co ntrol has the foc us:
Screen.Acti veC ontrol

You can use this fragment just like any other reference to a control. If you know that the
co ntrol is a text box , you can refer to any of the properties supported for tex t boxes,
including Text, Se!Text, and Se!Length. This code assumes that the active co ntrol is a text
box , and it refers to SetText:
Sub CopyCmd_Click ()
Clipb oard.SetText Sc reen.ActiveControl .SelText
End Sub

Sub CutCmd Click ()


Clipboa rd .SetText Screen.Acti veControl .Se l Text
Screen . Acti veControl. Sel Text
End Sub

Sub PasteCmd Cl i ck ()
Sc reen.ActiveControl .SelText Clipboard .Get Text()
End Sub

Another useful Clipboard method is Clear, which clears ali contents of the Cli pboard. The
syn tax is :
Clipboard.Clear

Microsoft Visual Basic Programmer's Guide


Chapter 18 lnteracting with the Environment 267

The other Clipboard methods-GetData, SetData, and GetFormat-enable you to deal


with data formats other than text. The Clip board can actually han<lle a variety of data
formats, each represented by a number recognized by GetFormat and the other methods.
These forrnats are described below, along with the corresponding number and symbolic
name defined in CONSTANT.TXT.
Name in CONSTANT.TXT Value Description
CF_LINK &HBF00 Dynarnic-data-exchange
link. U se this data forrnat to
give the user dynarnic paste-
link capability. For more
information, see Chapter 22,
"Communicating with Other
Applications."
CF_TEXT 1 Text. Examples earlier in
this section all use this
format.
CF_BITMAP 2 Bitmap.
CF_MET AFILE 3 Metafile.
CF_DIB 8 Device-independent bitmap.

The last three forrnats (bitmap, metafile, and device-independent bitmap) are all used for
transferring graphic images. For example, the following code copies a picture using bitmap
forrnat (assuming that the constant CF_BITMAP is defined as equal to 2):
Sub Copy ()
Clipboard.SetData Picturel.Picture, CF_BITMAP
End Sub

This code pastes the bitmap picture on the Clipboard into Picturel:
Sub Paste ()
Picturel.Pi ct ure - Clipboard.GetOata(CF_BITMAP)
End Sub

You can use the GetFormat method to determine whether a given data forrnat matches the
data on the Clipboard.
For more inforrnation on the Clipboard object, see the Language Reference, or:

m Search Help for:


Clipboard object

Microsoft Visual Basic Programmer's Guide


Part 4 Advanced Applications

Using Timer Controls


Timer controls respond to the passage of time. They are independent of the user, and you
can program them to take actions at regular intervals. A typical response is checking the
system clock to see if it is time to do sorne task. Timers also are useful for other kinds of
background processing.
Eaéh timer has an Interval property, whi ch specifies the number of milliseconds th at pass
between one timer event and the next. Unless disabled, a timer continues to receive an event
(appropriately named the Timer event) at roughly equal interval s of time.
The Interval property has a few limitations to consider when you ' re programming a timer:
• The interva1 can be between Oand 64,767 , inclusive, which means that even the longest
interva1 ca n' t be much longer th an one minute (about 64 .8 seco nds) .
• The interva l is not guaranteed to elapse exactl y on time. To ensure acc uracy, the tim er
should check the system clock when it needs to, rather than try to keep track of
accumulated time intern ally .
• The system generates 18 clock ticks per second, so even though the Interv al property is
measured in milliseconds, the true precision of an interval is no more than one-ei ghtee nth
of a second .

Every timer control must be associated with a forro . Therefore, to create a timer applicati on.
you must create at 1east one form . As explained in Chapter 15, "Creating Multiple-Form
Applicati ons," you can load a forro without maki ng it visible.

Note The word "tim er" is used in severa] ways in Visual Bas ic, eac h closely related to th e
workings of the timer co ntro l. In addition to the control name and control type, "timer" is
used in th e Timer event and the Timer fun ction . (The latter return s the number of seco nds
e lapsed since midni ght. )

Placing a Timer Control on a Form


Pl ac ing a timer co ntrol on a fo rm is like drawing any other co ntro l: Click the timer too! in
the Toolbox, and drago n a form. Or, double-click the timer too! to create a default-size
timer on the current form , as shown in Figure 18.2. The latter technique often works best,
because the size and position of the timer control don ' t matter at run time.

1m Forml Da

.
.
-~ -
. .- ~V ..

Figure 18.2 A timer control

Microsoft Visual Basic Programmer's Guide


Chapter 18 lnteracting with the Environment 269

The timer appears on the form at design time only so you can select it, view its properties,
and write an event procedure for it. At run time, a timer is invisible and its position and size
are irrelevant. In fact, it has no size or location properties.
For more information on drawing controls, see Chapter 6, "Drawing the Interface," or:

Search Help for: . . See Tutorial Lesson:


111 draw controls M uWorking with Visual Basic"

lnitializing a Timer Control


A timer control has only four properties. At design time, you should set them as follows .
Property Setting
CtlName A descriptive name for the timer.
Enabled If you want the timer to start working as soon as the form
loads, set to True (-1). Otherwise, leave this property set to
False (O) . You may choose to have an outside event (such as
a click óf a command button) start operation of the timer.
Interval Number of milliseconds between timer events.
Index Not used, unless the timer is an element of a control array.

Note that the Enabled property for the timer is different from the same property for other
objects. With most objects, the Enabled property determines whether the object can respond
to an event caused by the user. With the timer control, setting Enabled to False suspends
timer operation.
Remember that the Timer event is periodic. The Interval property doesn't determine "how
long" as much as it determines "how often." The length of the interval should depend on
how much precision you want. Because there is sorne built-in potential for error, make the
interval one-half the desired amount of precision.

Note The more often a timer event is generated, the more processor time is eaten up in
responding to the event, and this can slow down overall performance. Don't set a
particularly small interval unless you need it.

Responding to the Timer Event


When a timer control's interval elapses, Visual Basic generates the Timer event. Typically,
you respond to this event by checking sorne general condition, such as the system clock.

Microsoft Visual Basic Programmer's Guide


270 Part 4 Advanc ed Application s

A di gital clock is a very simple but hi ghly useful application involving a timer control. Once
you understand how the application works, you can enhance it to work as an alarm clock,
stopwatch, or other timing device.
The Digital Clock application includes a label with a border, and a timer. The application
looks like Figure 18.3 at design time.

al Forml DII
'-------
llabel- 1 -~I ~ :
Figure 18.3 The Dig ital Clock Application

At run time, the picture of the timer does not ap pear.


The label' s BorderStyle property is set to " 1 -Thin," and the caption is blank. The timer's
Interval property is set to 1000, and the Enabled property is set to True (-1).
The sole procedure in the application is an event procedure for the timer:
Sub Timerl _Timer ()
Labell.Caption = Time$
End Sub

The procedure displays the system time by calling the intrinsic Time$ function. This
function retums a string showin g the current time in a convenient hh :mm:ss formal.
You can customi ze the look of the Digital Clock without having to write any addition al
statements. For exa mple, you mi ght want to select a different font for the label, or change
the BorderStyle property of the form.
The Time$ fun ction shows the time in 24-hour format , so that 11 P.M. is represented as:
23 :00:0 0

To display time in A.M .IP.M. formal, the procedure must alter the time string before copying
it to the la bel :
Sub Timerl _Timer ()
Di m MyTi me As String
Dim Hours As Integer

MyTime = Time$
Hour s = Val(MyTime)
If Hours > 12 Then Mid$(MyTime, 1, 2) Str$(Hours - 12)
Labell.Caption - MyTime
End Sub

Microsoft Visual Basic Programmer's Guide


Chapter 18 lnteracting with the Environment 271

This procedure starts by storing the system time in a temporary string variable, MyTi me .
Then it extracts the first two digits :
Hours - Val(MyTime)

The Val function reads digits until it encounters a character that is not numeric: in this case,
it stops reading digits when it encounters the first colon (:), which immediately follows the
two hours digits. The function retums the numeric value of these digits. This gives you the
number of hours .
For more information on the Val function , see the Language Reference, or:

m Search Help for:


Val

To extract minutes or seconds from a string variable, use the Mid$ function.
This statement tests to see if the number of hours is greater than 12. If so, it uses the Mid$
function to replace the first two digits with the number of hours minus 12:
If Hours > 12 Then Mid$(MyTime. 1, 2) - Str$(Hours - 12)

The Mid$ function retums a substring. The arguments to Mid$ give the string to dissect, the
starting position (in which 1 is the first character), and length of the substring on which to
operate. Therefore, Mi d$ ( MyTi me, 1, 2) refers to a substring of MyTi me that begins in
the first position and is two characters long.
For more information on the Mid$ function , see the Language Reference, or:

m Search Help for:


Mid$

Building an Alarm Clock


Building an alarm clock involves only a little more programming than the Digital Clock:
The Alarm Clock application is given an alarm time, and on each clock tick, the clock
checks to see if the time has been reached. If so, it informs the user.
The alarm time is stored in a string declared in the Declarations section of the form:
Dim AlarmTime As String

To set the alarm time, the user clicks the blank portion of the forrn. (Altematively, this can
be irnplemented as a menu command oras a command button.) The procedure prompts the
user for a time by usi ng the InputBox$ statement. If the user presses the Cancel button on
the input dialog box, the lnputBox$ function r:etums an empty string. Therefore, the
procedure assigns a new value to the alarm time only if the string returned is not empty.
Sub Form_Click ()
Temp$ = InputBox$("Enter alarm time in 24-hour hh : mm: ss format:")
If Temp$ <> "" Then AlarmTime - Temp$
End Sub

Microsoft Visual Basic Programmer's Guide


272 Part 4 Advanced Applications

The Time r event now compares the current time to the string stored in Al a rmTi me . After
updating the time di splay , the Timer event checks to see if the alarm time has been reac hed
yet. If so, it alerts the user:
Sub Timerl _Timer ()
Labell .C aption - Time$
If Time$= AlarmTime Then
Be ep: Beep: Beep
MsgBox "Alarm has sounded ."
End I f
End Sub

Thi s code works fine as long as the clock is not interrupted at th e wrong time. The
application can run in the background, and will beep and di spl ay the message box eve n
though it does n' t have the focu s. However, exec ution is suspended any time the user i~
moving the form.
If the application is not active on the same second that the alarm time is reached, the alarm is
never sounded. The following variation to the Timer event enables the Alarm Clock to report
the alarm time as soon as it can, even if execution was suspended when the time was
reached:
Sub Timerl _Timer ()
Const TRUE = - 1, FALSE = 0
Static AlarmSounded As Integer

Labell.Ca ption = Time$


If AlarmT ime = '"' Then Exit Sub
If Time$ >= AlarmTime and Not AlarmSounded Then
Beep : Beep: Beep
MsgBox "Alarm has sounded. "
AlarmSoun ded - TRUE
Elself Time$ < AlarmTime Then
AlarmSo und ed = FALSE
End I f
End Sub

In thi s ve rsion , the procedure tests to see if the current time is greater than or egu a! to alarm
time. Thi s way the application can detect whether the alarm should go off, even if it is
returnin g from a suspended state and was not ac tive at the alarm time. The stati c variable
Al a rmSounded ensures that the alarm goes off only once in each 24- hour cyc le.

Note The examples in this secti on ass ume 24- hour formal for the time. However, yo u can
rewrite them to adopt A.M./P.M . format usi ng th e techniques shown at the e nd of the
previous section . When using a different formal, store the alarm time intern ally in th e
standard 24-hour format (for ease of co mparison to Time$). Then convert for A.M./P.M .
on ly when ge ttin g input or di splaying output.

Microsoft Visual Basic Programm er's Guide


Chapter 18 lnteracting with the Environment 273

Writing ldle Loops with DoEvents


Normally, Visual Basic executes statements only in response to events. The time between
events is referred to as "idle time."
You can write a loop that executes statements only when nothing else in the environment
requires immediate attention. Such a loop is sometimes called an idle loop. In most cases,
you should design your applications around events rather than writing idle loops.
But if you do need certain statements or calculations to be performed continually, you
definitely should use an idle loop. Unless restricted to idle time, an indefinite loop takes over
the processor and doesn't permit other parts of the environment to respond to events. This
makes the whole environment unresponsive.

.,.;ortant Multitasking in Microsoft Windows is not preemptive. Thi s means that Windows depends
on each individual application to yield time voluntarily before it can service another
application.

To write an idle loop, add a module to the project and place a procedure called Main there.
This has the effect of making this module the startup module. (As a result, no form is
automatically loaded on startup, so you may need to use Load statements.) Write a Do
While loop that uses the DoEvents function :
Sub Main ()
Forml.Show • Optionally, you can lo ad and di s play a form.
Do While DoEvents()
' Place idle-loop code here.
' These statements are processed whenev e r t he sys tem has free time.
Loop
End Sub

An idle loop might be useful in a communications program (for example, a stock market
ticker) that continually monitors data. Another use of a DoEvents loop is creating an alarm
clock, though a timer control is more appropriate for doing that.
The DoEvents function switches control over to the operating environment kernel. It retums
as so,on as ali other applications in the environment have had a chance to respond to pending
events . This doesn't cause the current application to give up the focus , but it does enable
background events to be processed. For example, if the Alarm Clock application from the
previous section is running in the background, calling DoEvents gives the clock a chance to
update its display .
DoEvents retums the number of forms in the application that are currently loaded. In the
code example above, the DoEvents loop terminates when no forms are loaded. Also note
that if any procedure anywhere in your application executes the End statement, all code in
your application terminates unconditionally.

Microsoft Visual Basic Programmer's Guide


zn Part 4 Advanced Applications

To call DoEvents, you must store the retum value somewhere. lf you don't want to use the
value, store the return value in a dummy variable:
Dummy - DoEvents() ' Relinquish time to other applications.

DoEvents is useful if you have a long mathematical calculation, and you don ' t want to slow
down the responsiveness of the environment. However, be careful when using DoEvents
thróughout your application. A procedure that has given up control with DoEvents must not
be executed again before DoEvents retums. Otherwise, the procedure may end up being
called endlessly, until system resources are exhausted.
For example, this procedure tests for prime numbers, and uses DoEvents to periodically
enable other applications to process events:
Function PrimeStatus (TestVal As Long) As In t eger
Co nst TRUE = - 1 . FAL SE - 0
Dim Lim As Integer

PrimeStatus - TRUE
Lim = Sqr (TestVal)
For I = 2 To Lim
If TestVal Mod I - 0 Then
PrimeStatus - FALSE
Exit Far
End I f
If I Mod 200 = 0 Then Dummy = DoE vents()
Next I
End Function

The second-to-last line calls DoEvents once evcry 200 iterations. This statement allows the
PrimeStatus Function procedure to continue calculations as long as needed while the rest of
the environment responds to events.
With this example, you must ensure that PrimeStatu s is not called again before DoEvents
returns . Consider what happens during a DoEvents call . Execution of application code is
suspended while other forms and application s process events . One of these events rnight be a
button click that launches the PrimeStatus procedure again. This would cause PrimeStatus to
be re-entered before DoEvents could return .

Mic rosoft Visual Basic Programmer's Guide


Chapter 18 lnteracting with the Environment 275

The solution is to prevent this from happening. For example, if the PrimeStatus Function
procedure is launched by a click on a command button, then don't make it possible for
PrimeStatus to be called again until it retums. The code for this command button might be:
Sub StartPrimeTest_Click ()
Const TRUE - - 1, - FALSE - 0
Static AmCalculatingNow As Integer

If AmCalculatingNow Then Exit Sub


N - Val (Readout)
AmCalculatingNow - TRUE
TestResult - PrimeStatus (N)
AmCalculatingNow - FALSE
End Sub

One of the effects of DoEvents is to give forms and windows a chance to respond to Paint
events, so DoEvents can be used to update the display. However, because of the
complications just described, DoEvents is not the safest way to cause screen updates. Use
the Refresh method instead. For more information on the Refresh method, see the
Language Reference, or:

Search Help for:


111 Refresh

Writing Low-Level Keyboard Handlers


The KeyDown and KeyUp events provide the lowest level of keyboard response. Use these
events to detecta condition that the KeyPress event is unable to detect, including:
• Special combinations of SHIFT, CTRL, and ALT keys.
• Arrow keys. Note that sorne controls (command buttons, option buttons, check boxes) do
not get arrow key events. Instead, arrow keys cause movement to another control.
• PAGEUP and PAGEDOWN.
• Distinguishing the numeric keypad from numbers on the typewriter keys.
• Responding to a key being released as well as pressed (KeyPress responds only to a key
being pressed).
• Function keys not attached to menu commands.

Before writing a low-level keyboard handler, make sure that the KeyPress event isn't
sufficient. This event detects keys that correspond to all the standard ASCII characters,
including all alphanumeric keys anda number of others, including BACKSPACE, ENTER, and
TAB. It's generally easier to write code for the KeyPress event.
You also should consider using shortcut and access keys, described at the end of Chapter 10,
"Responding to Commands." Shortcut keys must be attached to menu commands, but they
can include function keys (including sorne function-key- shift-key combinations). These
keys have the virtue of requiring no additional code.

Microsoft Visual Basic Programmer's Guide


276 Part 4 Advanced Applications

KeyDown and KeyUp Compared with KeyPress


The KeyDown and KeyUp events provide inforrnation in a different forro from the KeyPress
event. This is because KeyDown and KeyUp report the exact physical state of the keyboard
itself. These events do not interpret the keyboard state; you have to do that yourself.
The KeyPress event, in contrast, does not report the state of the keyboard directly. Instead, it
supplies a generated character.
An example helps to illustrate the difference. When the user types uppercase "A," the
KeyPress event gets the ANS I code for "A." The same thing happens when the user types
lowercase "a." In contrast, the KeyPress event sees these two keys as two separate
characters.
The KeyDown event returns information on the character typed by providing the following
two arguments.
Argument Description
KeyCode Indicates the physical key pressed. In this case, "A" and "a"
are retumed as the same key. They have the identical
KeyCode value. But note that "1" on the typewriter keys and
" 1" on the numeric keypad are returned as different keys,
even though they generate the same character.
Shift Indicates the shift-key state. Only by examining this
argument can you determine whether an uppercase or
lowercase letter was typed.

The keyboard even ts are not mutuall y exclusive. When the user presses a key, both the
Key Down and KeyPress events are ge nerated .

The KeyDown and KeyUp Events


Only the obj ect th at has the foc us can get a keyboard event. This includes KeyPress,
KeyDown , and KeyUp. For the purpose of keyboard events, a form has the foc us only if the
form is active and no control on that forro has the focus. This happens only on blank forros
and form s on which ali control s have been disabled.
For a text box with the default name Textl , the code templates for KeyDown and KeyUp
are :
Sub Text l _KeyD own (KeyCode As In t eger . Shift As Integer)

End Sub

Sub Tex tl _KeyUp (K eyCode As Int ege r. Shi ft As Integ er)

End Sub

The argument KeyCode is an integer that indicates the physical key that is pressed or
released. The key is represen ted by a numeric code found in the CONST ANT.TXT fil e.

Microsoft Visual Basic Programmer's Guide


Chapter 18 lnteracting with the Environment 277

The argument Shift is a bit-field argument (similar to the ones introduced in Chapter 14,
"Responding to Mouse Events") that retums the state of the SHIFf, CTRL, and ALT keys at the
time of the keyboard event.

The KeyCode Argument


The argument KeyCode identifies a key by a numeric code. You can load the definitions
from CONSTANT.TXT into the global module, or you can place selected key-code
definitions in a procedure or Declarations section of a form or module. If you don't place the
definitions in the global module, remove the keyword Global from the statement.
For example, sorne of the function-key codes are defined as:
Const KEY _Fl - &H70
Const KEY _F2 = &H71
Const KEY - F3 = &H72
Const KEY_ F4 - &H73
Const KEY - F5 - &H74

Key codes for letter keys are the same as the ANSI codes of the uppercase character of the
letter. So the KeyCode for both "A" and "a" is the value returned by Asc("A"). Key codes
for the number and punctuation keys are the same as the ANSI code of the number on the
key. So the KeyCode for both "l" and "!" is the value retumed by Asc("l"). Again, numeric
keypad keys are separate. They have their own special codes, as indicated in the file
CONSTANT.TXT.
For example, this procedure quits the application when the user presses F2:

Sub Te xtl _Key Oown (KeyCode As Integer, Shift As Integer)


Const KEY _F2 = &H71
If KeyCode - KEY_ F2 Then End
End Sub

For more information on ANSI codes, see the Language Reference.

The Shift Argument


The argument Shift is nearly the same as the Shift introduced in Chapter 14. This argument
returns the state of three keys-SHIFf, CTRL, and ALT-in the three least-significant bits.
The three keys correspond to the bit pattems 001, 010, and 100 respectively. To test for a
specific shift-key state, declare the following constants:
Const SHIFTKEY = 1
Const CTRL - 2
Const ALT = 4

You then can test for each shift-key state that you're interested in:
ShiftOown% = (Shift And SHIFTKEY) > 0
CtrlOown% = (S hift And CTRL) > 0
AltOown% - (S hi ft And ALT) > 0

Microsoft Visual Basíc Programmer's Guíde


278 Part 4 Advanced Applications

This procedure responds to the combination SHIFr+ALT+F2 by quitting the application:


Sub Textl _KeyDown (KeyCode As Integer, Shift As Integer)
Const SHIFTKEY - 1
Const CTRL - 2
Const ALT - 4
Const KEY _ F2 - &H71

ShiftDown% - (Shift And SHIFTKEY) > 0


AltDown% - (Shift And ALT) > 0
F2Down% - (KeyCode - KEY_ F2)

If Shift Down% And AltDown% And F2Down% Then End


End Sub

Note To improve readability and maintenance of your code, place ali the Shift and KeyCode
arguments in the global module.

Writing a General Keyboard Handler


Each KeyDown and KeyUp event is attached to a specific object. To write a keyboard
handler that applies to all objects on the form, write a general procedure that serves as the
form-wide keyboard handler, and then have each KeyDown procedure (or KeyUp procedure,
if appropriate) call the comrnon handler.
For example, for a form with two controls, you might have each object call a general
procedure named KeyDownHandler. Each KeyDown procedure passes along the arguments
KeyCode and Shift:
Sub Textl _KeyDown (KeyCode As Integer, Shift As Integer)
KeyDownHandler KeyCode, Shift
End Sub

Sub Picturel_KeyDown (KeyCode As Integer, Shift As Integer)


KeyDownHandler KeyCode, Shift
End Sub

Su b Form_KeyDown (KeyCode As Integer, Shift As Integer )


KeyDownHandler KeyCode, Shift
End Sub

The KeyDownHandler procedure itself actually responds to the keyboard conditions:


Sub KeyDownHandler (KeyCode As Integer, Shift As Integer)
Const Key_ F2 - &H71
If KeyCode - Key _F2 Then End
End Sub

Microsoft Visual Basic Programmer's Guide


Handling Run-Time Errors

You ' ve probably noticed that Visual Basic does a good job of catching errors that creep into
your code as you write. Visual Basic often warns you immediately if you have entered a line
of code that contains a syntax error. Similarly, Visual Basic provides tools for analyzing
code and isolating prograrn logic errors.
There are other errors that only appear when your code is running. These are called run-time

••
dling

• •
•• ••
• ••


280 Part 4 Advanced Applications

Why Use Error Handling?


Ideally, applications don ' t need any error-handling code. Unfortunately, we live in a world
where users forget to put disks in drives, and network drives sometimes disconnect
unexpectedly. If you want your applications to handle such surprises, write code to deal with
them.
The following procedure checks to see if a disk contains a fil e with the extension .TXT, but
does not contain error-handling code:
Sub CheckTxtFiles ()
' Use Dir$ to check far a .TXT file.
CheckName$ - Dir$("*.TXT")
If CheckName$ <> "" Then
Msg$ = "Th e fi rst . TXT fil e found was "
Msg$ = Msg$ + CheckName$
Else
Msg$ - " Sorry, no . TXT fil e was found"
End i f
MsgBox Msg$, 64, "TXT Fil e Sea rch"
End Sub

The code appears to cover either of the possible outcomes of the Dir$ call. However, if the
current drive is a floppy disk drive, this fragment will work correctly only if a disk is in the
drive and the drive door is closed. If this isn't the case, Visual Basic generares the error
message De vi e e un a va i l a b l e and halts execution of the appl ication. If the application
were running in the Visual Basic environment, the user could fix the error and resume
runnin g the program. But if the application were started from an executable file , it would
display a Visual Basic error message, then unload the application and retum the user to the
operating environmenl.
To avoid this situation , use the error-handling features in Visual Basic to intercept errors and
take corrective action. (lntercepting an error is also known as trapping an error.) For
example, device problems such as the disk not in drive or drive door not closed could be
handled by using the following code.

M ic rosoft Visual Basic Programmer's Guide


Chapter 19 Handling Run-Time Errors 281

Sub CheckTxtFiles ()
' Define constant to represent Visual Basic error code .
Const ERR_DISKNOTREADY = 71, ERR_DEVICEUNAVAILABLE = 68
' Define constants for message - box types.
Const MB_EXCLAIM = 48, MB_STOP = 16

' Turn on error trapping. This causes a branch to t he error handler


' if any error is detected.
On Error GoTo CheckError

' Use Dir$ to check for file with . TXT extension.


CheckName$ = Dir$("*.TXT")

' Avoid executing error handler if no error occurs.


Exit Sub

' Branch here if error occurs.


CheckError:
If (Err = ERR_DISKNOTREADY) Or (Err = ERR_DEVICEUNAVAILABLE) Then
Msg$ = "Put a floppy disk in the dri ve and el ose the dri ve door."
' Display message box with exclamation icon and OK button .
MsgBox Msg$, MB_ EXCLAIM
Else
Msg$ = "Unanticipated error number" + Str$(Err) +" occurred: "+ Error$
' Display message box with Stop sign icon and OK button .
MsgBox Msg$, MB_STOP
Stop
End I f
Resume
End Sub

The Err function retums the number associated with the run-time error that occurred;
Error$ retums the Visual Basic message associated with the error. Should Vis ual Basic
generate the error Disk n ot rea dy or Dev ice un a va i la ble, a message is displayed
telling the user what to do. The Resume statement immediately preceding End Sub then
retums control to the statement at which the error occurred and attempts to execute it again.
If the user has corrected the problem, the statement succeeds; otherwise, the program
branches to the error handler again . If an unanticipated error occurs an alternative message is
presented and the program ends . See the section "Guidelines for Complex Programs" for an
explanation of using the Stop statement.
Your application can correct many kinds of errors, or prompt the user to change the
co nditions that ca used the error, using techniques such as those shown in the preceding
example . The nex t section discusses these techniques in detail.

Microsoft Visual Basic Programmer's Guide


Part 4 Advanced Appli cation s

How to Handle Errors


The error-handling code in the preceding example involves three steps:
l . Set an error trap by telling the application where to branch to (in other words, which
error-handling routine to execute) when an error occurs. Setting an error trap also is
called enabling an error trap .
The On Error statement enables the trap, which in tum directs the application to the
label CheckError: .
2. Write a routine th at takes acti on based on any errors you can anticipate - the error-
handling routine. If control actu all y branches into the trap at sorne point, the trap is then
said to be active .
The CheckE r ror routine ha ndles the error using an If... Then ... Else statement
conditioned on the value retumed by the Err function . Err returns a numeric code
corresponding to the error m essage that Visual Basic generates. In the example, if Di s k
n ot re a dy or De vi ce un a v a i la bl e is generated, a m essage prompts the u ser to close
the drive door. If a different error is generated, an appropriate message is displayed, and
the program stops. (For a list of Visual Basic run-time errors, see the Language
Ref erence .)
3. E xit the error-handling routine.
The Resume statem ent is used to branch back to the line where the Disk not ready or
De vi e e un a va i l a b l e error occ urred . An attempt is again made to execute the
statement that caused the error.

Details on how to perform these steps are prov ided in the follow ing secti ons. Refer to th e
example in the precedin g section as you read .

Setting the Error Trap


A n error trap is enabled w hen Visual Basic executes the On Error statem ent, in which an
error handl er is specified . The error trap remains enabled while the procedure containing it is
active. Th at is, the error trap is enabled until an Exit Sub, Exit Function, End Sub, or End
Function statement is exec uted for that procedure (unless it is explicitly turned off with a
special case of the On Error statem ent - On Error GoTo 0) . For more information about
di sabling en-ar handling, see the sec ti on "T urning Off Error H andling" later in this chapter.

Writing an Error-Handling Routine


T he first step in writing in an error-handlin g routine is pl acing the On Error GoTo line
stateme nt, where line indicates the !abe! identi fy ing the en-or-handling code. In the
preceding exampl e, the label was Check Erro r: (note th at the colon is part of the label, but
it is not used in the On Error GoTo line statement).
The error-handling routine is pl aced where it cannot be executed during normal appli cation
fl ow. lt is no rm a ll y positi o ned between an Exit Sub (or Exit Function) and an End Sub (or
End Function ) stateme nt , as show n in the preceding exa mpl e.

Mic rosoft Visual Basic Programmer 's Guide


Chapter 19 Handling Run-Time Errors 283

The Err function returns a numeric code representing the most recent run-time error. (As
mentioned earlier, a run-time error can occur only when your code is running.) By using Err
in combination with Select Case or lf... Then ... Else statements, you can take specific action
for any error that occurs .

Note The string returned by Error$ always explains the error associated with the current
error number. However, precise wording of the message may vary among versions of the
product.

Exiting an Error-Handling Routine


The preceding example used a Resume statement within the error handler to re-execute the
statement that had originally caused the error. There are other ways to exit from an error-
handling routine. Depending on circumstances, you may choose any of the statements shown
in the following table.
Statement Description
Resume Re-executes to the statement that caused the error.
Resume Next Resumes program execution at the statement immediately
following the one that caused the error.
Resume line Resumes program execution at the label specified by line,
where line is a nonzero line number or line label.
Error Err Triggers a run-time error. When this statement is executed
within the error-handler routine, a search begins along the
invocation path for another error-handling routine. (The
invocation path is the chain of procedures that has been
invoked to arrive at the current point of execution.) For
more information, see the section "Unanticipated Errors"
later in this chapter.

Resume returns to the statement that caused the error. Use it to repeat an operation after
correcting the error.

Microsoft Visual Basic Programmer's Guide


284 Part 4 Advanced Applications

The Resume Next statement returns to the statement immediately following the one that
caused the error. The difference between Resume and Resume Next is shown in Figure
19.1.

Start

Resume

1
l
Statement with error . Error handler

Statement following • Resume Next


the one with the error

( End )
~-~

Figure 19.1 Program fl ow with Re sum e an d Re sume Next

Whether you use Resume or Resume Next depe nds on whi ch source changes th e condition
that led to the error - either the user mu st make the change, or the code fo r yo ur appli cati on
does. If the user can make th e change (s uch as closing a dri ve door), Resume is probably
appropri ate. However, your error handler may be written so that the existence of a run-time
error is never revealed to th e user.
In the fo ll owing code fragme nt, a di vision is performed with two variables. If the numerator
is nonzero, but the denomin ator happens to be zero , Vi sual Basic generates the error
Oi vi s i on by z e r o. If both are zero (and flo ating-point di vision is being perforrned),
Visual Bas ic generates the error Ov e rflow . In these cases the Function procedure could
simpl y ret urn the largest va lue of its ty pe (thu s simulating infinity) .

Micros oft Visu al Basic Programmer's Guide


Chapter 19 Handling Run -Time Errors 285

Function Dividelt CX As Single, Y As Sing le)


On Error GoTo MathHandler
Dividelt = X/Y
Exit Function
MathHandler :
If Err = 11 Or Err = 6 Then · If error was Division by zero or
Dividelt = 3.4E38 • Overflow. simulate infinity by returning
Else ' the l argest sing l e-precis ion value .
MsgS - "Unanticipated error"+ StrS(Err) +" occurred: "+ Error$
MsgBox Msg$ , 48 ' Show message with an exclamation point.
End I f 'In all cases, Resume Next continues execution
Resume Next ' at the Exit Function statement .
End Function

Resume Next also can be used if you anticípate an error in a loop, and you need to restart
the operation. Or, you can use Resume line, which returns control to a specified line label.
The following example enables the user to enter file specifications to check until Dir$
returns without errors, or choose Cancel at the InputBox to exit from the procedure.
Function VerifyFile () As String
Const ERR_BADFILENAME = 52, ERR_DRIVEDOOROPEN = 71
Const ERR_DEVICEUNAVAILABLE = 68, ERR_IN VA LIDFILENAME = 64
Const FALSE= 0. TRUE - Not FALSE
NLS = Chr$(13) + Chr$(10) ' Carriage return-linefeed comb ination.
PromptS = "Enter file specification to check:"
StartHere:
FileSpecS = "" • Start with a default specification.
Msg$ = MsgS + NL$+ PromptS
'Let the user modify the default .
File Spec$ = InputBoxS(MsgS, "File Search", FileSpecS, 100, 100)
If Fil eSpecS = "" Then Exi t Funct ion • Exi t i f user enters nothi ng.
On Error GoTo Handler
VerifyFile = DirS(FileSpecS)
Exit Function
Handl er:
Se l ect Case Err ' Analyze error code, then load up message .
Case ERR_ INVALIDFILENAME, ERR_BADFILENAME
Msg$ = "Your file specification was invalid, try another:"
Case ERR_DRIVEDOOROPEN
Msg$ = "Clase the disk drive door and try again:"
Case ERR_DEVICEUNAVAILABLE
Msg$ = "The drive you specified was not found . Try again:"
Case Else
Error Err
End Select
Resume Start Here ' This j umps back to label so user can
End Funct ion ' try another filename .

Microsoft Visual Basic Programmer's Guide


Part 4 Advanced Applications

If a file matching the specification is found, its path and name are returned. If Dir$ returns
an empty string, the function is executed. If one of the anticipated errors occurs, a message is
assigned to Ms g $ and execution jumps back to the label StartHere, and the user has another
chance to enter a valid path and file specification:
Although Resume fine is a legitimate way to perform this operation, jumps to labels are
ofü~n considered throwbacks to a less structured style of programming, since their
proliferation can make code difficult to understand and debug.
The previous example also illustrates how to use an Error statement to regenerate an
unanticipated error within the error-handling routine itself. This causes Visual Basic to
search back through the invocation path (if there is one) for another error-handling routine.
The next section, "Unanticipated Errors," explains the invocation path and how Visual Basic
searches back through it.

Unanticipated Errors
As previously noted, an enabled error handler is one that has been turned on by executing an
On Error statement, and has not yet been tumed off-either by an On Error GoTo O
statement, or by exiting the procedure from which it was tumed on. An active error handler
is one in which execution is currently taking place. An error handler must be enabled to be
active, but it need not be active simply because it is enabled.
When an error occurs within a procedure that does not have an enabled error-handling
routine, or when an error occurs within an active error-handling routine, Visual Basic
searches the invocation path for another enabled error-handling routine.
Consider the following path of invocati on:
• Form_Load procedure calls Procedure A
• Procedure A calls Procedure B
• Procedure B calls Procedure C

While procedure C is execu tin g, th e invocation path is Form_Load, A, B,C. The procedures
Form_Load, A, and B are pending while Procedure C is executing. If an error occurs in
Procedure C and the procedure does not have an enabled error handler, Visual Basic
searches back through the invocation path - first Procedure B, then Procedure A, then
Form_Load . Visual Basic executes the first enabled error handler it finds. If it reaches
completely back along the invocation path without encountering an enabled error handler in
any of the pending procedures, it di splays the appropriate message and halts execution .

Microsoft Visual Basic Programmer's Guide


Chapter 19 Handling Run-Time Errors 287

If Visual Basic finds an enabled error-handling routine, execution continues in that error-
handling routine. If a Resume ora Resume Next statement is executed in the error-handling
routine, execution continues as shown in the following table.
Statement Result
Resume Visual Basic re-executes the call to the procedure that
Visual Basic just searched back through. In the invocation
path given earlier, if Procedure A has an enabled error-
handler that includes a Resume statement, Visual Basic re-
executes the call to Procedure B.
Resume Next Execution retums to the statement following the last
executed statement in that procedure. This is the statement
after the call to the procedure that Visual Basic just searched
back through. In the invocation path given earlier, if
Procedure A has an enabled error-handler that includes a
Resume Next statement, execution retums to the statement
after the call to Procedure B.

Note that the statement executed is in the procedure where the error-handling procedure is
found , not necessarily in the procedure where the error occurred. If you don't take this into
account, your application may perform in ways you do not intend.
An unanticipated error can occur within a procedure that has an enabled error handler, if the
range of errors does not include the one that actually occurred. In such a case, the procedure
could execute endlessly, especially if the handler executes a Resume statement To prevent
such situations, use the Error statement in a Case Else clause to actually generate an error
within the error handler; Vi sual Basic th en searches along the invocation path far a handler
that candeal with the error.
In the preceding example, the VerifyFile Function procedure, the number originally
retumed by Err was given asan argument to the Error statement in a Case Else clause,
generating an error. When this occurs within an active error handler, the search back through
the invocation path begins.

Note The effect of the search back through the invocation path can be hard to predict, since
it depends on whether Resume or Resume Next is executed in the handler that finally
processes the error successfully. For exampl e, if a Resume Next statement is executed to
exit the successful error trap, it retums to a statement in the procedure in which Resume
Next is executed, but that procedure may not be the one in which the error originally
occurred.

Microsoft Visual Basic Programmer's Guide


288 Part 4 Advanced Applications

Guidelines for Complex Programs


When you write large Visual Basic applications that use multiple forms and modules, the
error-handling code can get quite complex. Keep these guidelines in mind when writing
complex applications:
• Put an Error Err statement in all error-handling routines for cases where no code in the
error-handling routine deals with the specific error. This enables your application to try
to correct the error in other error-handling routines along the invocation path. This also
ensures that Visual Basic displays an error message if an error occurs that your
application doesn ' t handle. When you test your application this will help you uncover the
errors yo u are not handling adequately.
• If you choose not to use Error Err, you can write a fail-safe error-handling procedure
that ali your error handlers can call as a last resort. For exarnple , such a procedure rni ght
atternpL to save the user' s data before the application terminates.
• Use the Stop statement to force termination if you don't want a previous procedure to
trap the error. Using Stop enables you to examine the context of the error while
developing the prograrn. If the application is invoked from a stand-alone .EXE file, the
Stop staternent's behavior is identical to that of the End statement.

Centralized Error Handling


When you add error-handling code to your applications, you'll quickly discover you ' re
handling the same errors over and over. With careful planning, you can reduce code size and
save effort by writing a few procedures that your error-handling code can cal! to handle the
common eITor situations .
The FileErrors Function procedure that follows di splays a message appropriate Lo the error
that occurred, and where possible enables the user to cho ose a button to spec ify what action
the program should take next. It then retums acode to the procedure that called it. The value
of the code indicates which action in a group of actions to take. Note that constants such as
ERR_DEVICEUNAVAILABLE must be defined sornewhere (globally, or at the module
leve! of the module containing the procedure, or within the procedure itself) . The constant
MB_EXCLAIM is defined in the file CONSTANT.TXT.

Microsoft Visual Basic Programmer's Guide


Chapter 19 Handling Run-Time Errors 289

Function FileErrors (errVal As Integer) As Integer


' Return Value Meaning Return Value Meaning
' 0 Resume 2 Unrecoverable error
' 1 Resume Next 3 Unrecognized error
msgType% = MB EXCLAIM ' Defined in CDNSTANT.TXT.
Se l ect Case err Val
Case Err_DeviceUnavail abl e ' Error #68
Msg$ = "That devic e appears unavailable."
msgType% = MB_ EXCLAIM + 4
Case Err_DiskNotReady ' Error #71
Msg$ ="Inserta disk in the drive and close the door ."
Case Err_DeviceIO ' Error #57
Msg$ = "Internal disk error."
msgTyp e% = MB_EXCLAIM + 4
Case Err DiskFull ' Error #61
Msg$ = "Di sk is full. Conti nue?"
msgType% = 35
Case Err_BadFilename, Err_BadFilenameOrNumber ' Errors #64 & 52
Msg$ = "That filename i s illegal."
Case Err_PathDoesNotExist ' Error #76
Msg$ - "That path doesn't exist."
Case Err BadFileMode ' Error #54
Msg$ = "Can't open your file for that type of access . "
Case Err_ FileAlreadyüpen ' Error #55
Msg$ = "This file is already open . "
Case Err_ InputPastEndOfFile ' Error #6 2
Msg$ "Thi s file has a nonstandard end-of-f ile marker . "
Msg$ = Msg$ +"oran attempt was made toread beyond "
Msg$ - Msg$ + "the end-o f -file marker . "
Case El se
FileErrors = 3
Exit Function
End Se lec t
response% - MsgBox (Msg$, msgType%, "Disk Error")
Select Case response%
Case 1.4 'OK, Retry butt ons.
FileError s = 0
Case 5 ' Ignor e button.
FileErrors = 1
Case 2,3 ' Cancel, Abort buttons.
FileErrors = 2
Case Else
FileErrors 3
End Select
End Function

Microsoft Visual Basic Programmer's Guide


290 Part 4 Advanced Applications

This Function procedure handles common file- and disk-related errors. If the error is not
related to disk VO , it returns the value 3. The procedure that calls this Function procedure
should then either handle the error itself or call another procedure to handle it.

Note As you write larger and larger applications you'll find that you are using the same
constants in severa! procedures in various forms and modules . Moving the declarations for
those constants to the global module may better organize your code and save you from
typin g the same declarations over and over.

You can simpli fy error handling by calling the FileErrors procedure wherever you have a
procedure that reads or writes to disk. For example, you' ve probably used applications that
warn you if you will be overwriting a preexisting disk file when you try to save a file with a
certain name . Conversely , when you try to ope n a nonexistent file, many applications warn
you that the file does not exist, and ask if you want to create it. In both instances, errors can
occur when the application passes the filename to the operating system.
The following checking routine uses the value returned by the FileErrors procedure to decide
what action to take in the event of a disk-related error:
Function ConfirmFile (TheName As String, Operation As Integer) As Integer
' Parameters:
' TheName File spec to be checked for and confirmed.
'Operation Code for sequential file access mode (Output, Input, etc).
Note procedure works for binary and random because messages are
conditioned on Operation being <> to certain sequential modes.
' Returns:
1 Con firm s operation wil l not cause a problem.
' 0 User decided not to go through with operation.

Const SA VE FILE = l. LOADFILE = 2


Const REPLACEFILE = 1, READFILE 2
Const ADDTOFILE = 3 , RANDOMFILE 4 , BINARYFILE = 5

NL$ = Chr$(13) + Chr$(10) ' Ca rriage return-Linefeed combination.


On Error GoTo ConfirmFileError ' Tur n on the error trap.
TheFile$ = Dir$(TheName) ' Se e if the file exists.
On Error GoTo 0 ' Turn error trap off.
If user is sa ving text to a file that already exists ...
If TheFile $ <> "" And Operation = REPLACEFILE Then
Msg$ "The file"+ TheName$ + "already exists on disk."+ NL$
Msg$ Msg$ + "Sa ving the text box contents to that file will" + NL$
Msg$ Msg$ + "de stroy the file's current co ntents, replacing" + NL$
Msg$ Msg$ + "th em with the text from the text box." + NL$ + NL$
Msg$ Msg $ + "Choo se OK to overwrite the file. Cancel to stop."+ NL$
Confirmation% = Msg8ox(Msg $, 65, "File Message " )

M icrosoft Visual Basic Programmer 's Guide


Chapter 19 Handling Run-Time Errors 291

' If user wants to load text from nonexistent file ...


Elseif TheFile$ = "" And Operation = READFILE Then
Msg$ - "The file"+ TheName +" doesn't exist." + NL$
Msg$ - Msg$ + "Would you like to create and then edit it?" + NL$ +NL$
Msg$ - Msg$ + "Choose OK to create the fi l e, Cancel to stop."
Confirmation% = MsgBox(Msg$, 65, "File Message")
' If TheFile$ doesn't exist. force procedure to return
' 0 by setting Confirmation% = 2.
El seif TheFil e$ - "" Then
If Operation - RANDOMFILE Or Operation - BINARYFILE Then
Confirmation% = 2
End If
' If the file exists & operation isn't successful.
' Confirmation = 0 & procedure returns l.
End I f
If no box wa s displayed, Confirmation% = 0; if user chose OK
in either case, Confirmation = 1 and ConfirmFile should return l.
' to confirm that the intended operation is OK. If Confirmation% > 1
' ConfirmFile should return 0, because user doesn't want to go through
· with the operation ...
If Confirmation% > 1 Then ConfirmFi l e = 0 El se ConfirmFil e - 1
If Confirma tion% = 1 Then
If Operation = LOADFILE Then ' User wants to create the file. So assign
Operation = REPLACEFILE ' REPLACEFILE to Operation so caller will
End If ' understand action to be taken. Return code
End I f ' confir ming desire to eit her overwrite existing
· file or create new file.
Exit Function
ConfirmFileError:
Action% = FileErrors(Err)
Select Case Action %
Case 0
Resume
Case 1
Resume Next
Case 2
Exit Function
Case Else
Error Err
End Select
End Funct ion

Microsoft Visual Basic Programmer's Guide


2g2 Part 4 Advanced Application s

The ConfirmFile Function procedure recei ves a specification for the file whose existence
will be confirmed , plus information about which access mode will be used when an attempt
is made to actually open the file . If a sequen ti al file is to be saved (RE PLACE FIL E), and a
file is found that already has that name (and will therefore be overwritten), the user is
prompted to confirm that overwriting the file is acceptable.
If a s~quential file is to be opened (READFI LE), and the file is not found, the user is
prompted to confirm the desire to create the file . If the file is being opened for random or
binary access, its existence or nonexistence is either confirmed (return value 1) or refuted
(return value O) . If an error occurs in the call to Dir$, the FileErrors Function procedure is
called to analyze the error and prompt the user for a reasonable course of action. Like
FileErrors, ConfirmFile is used in the applications presented in chapter 21, "Processing
Files."

Delayed Error Handling


You may be used to programming in a language that does not interrupt your code when
errors occur but instead records the errors for you to check later. The C programming
language works this way, and you may sometimes find it convenient to use the technique in
Visual Basic programs. To do thi s, use the On Error Resume Next statement to tell Visual
Basic to record errors without interrupting the application.
Follow the On Error Resume Next statement with code that deals with the errors when it is
convenient. The code can tell if an error occurred by checking the value returned by the Err
function . If Err does not return zero, an error has occurred and the error-handling code ca n
take action based on the value of Err:
' Don't let an error disrupt the applicatio n.
On Err or Resume Next
Co ndi tion % = False
Do Unti l Condition% = True
' A l ong calculation loop that exits wh en Condition% becomes true.

LOOP
' Now see if an e rr or occur red and if so take action.
Se l ect Case Err
Case 0
' No error-continue with applicatio n.
Case Err _Overflow
' Deal wi th overflow error.
Ca se Err _Divi s ionByZero
' Deal with division by zero.
End Select
Program cont i nues here after checking far errors.

Microsoft Visual Basic Pro grammer's Guide


Chapter 19 Handling Run-Time Errors 293

In Chapter 20, "Using the File-System Controls," the event procedure Drivel _Change
illustrates the use of On Error Resume Next.
There are four points to remember when using delayed error handling:
• The code that detects and deals with the error differs from the error-handling routines
discussed earlier in this chapter-it does not contain any Resume statements.
• The error number returned by Err is the number of the most recent error. Any other
errors that occurred earlier in the preceding code are lost.
• If a Resume, Resume Next, oran On Error statement is executed, or if a procedure call
is made, Visual Basic resets Err back to zero. If you are going to use the value returned
by Err, store it in a variable before executing any of these statements.
• Finally, if errors occur and handling is deferred, logic errors in the intervening code
could com plicate things significantl y.

Another reason for using On Error Resume Next is to tailor error handling to each group
of related statements rather than have a single error-handling routine per procedure.

Turning Off Error Handling


If an error trap has been enabled in a procedure, it is automatically di sabled once the
procedure is exited. To explicitly turn off an enabled error trap, use the On Error GoTo O
statement. Once Visual Basic executes this statement, errors are detected, but not trapped
within the procedure. You can use On Error GoTo O to turn off error handling anywhere in
a procedure - even within an error-handling routine itself.
For example, try single stepping through a procedure such as this:
Su b DemoSub ()
On Error Go To SubHandler
' Error trapp ing is enabled.
' Err ors nee d to be caug ht and correcte d here .

Ki l l "OLDFI LE. XYZ"

On Error GoTo 0 ' Error trapping is turned off her e.

Foundlt$ = Dir$("OLDFILE .X YZ")

Microsoft Visual Basic Programmer's Guide


294 Part 4 Advanced Applications

On Error GoTo SubHandler


' Error trapping i s enabled again .
Ki 11 "OLDFI LE . XYZ"

Exit Sub
SubHandler:
' Error - handling routine goe s here .
Ms gBo x "Caug ht error . "

Resu me Nex t
End Sub

For more information on the various functions and statements you use to handle errors, see
the Language Reference, or:

m Search Help for:


error hand ling

Note Visual Basic doesn't use all available numbers for its own errors. As new errors are
defined for the Basic languages, the interna! error numbers increase. Also, other applications
may return error codes . If you want to generate and trap your own errors, begin your
numbering scheme with 32,767 and work your way down . This will ensure your error
numbers don ' t conflict with those of Basic or other applica ti ons.

Microsoft Visual Basic Programmer's Guide


Using the File-System Controls

Many applications must present information about disk drives, directories, and files. Visual
Basic includes powerful support for enabling users of your applications to explore the file
system. You can use three specialized file-system controls - the drive list box, the directory
list box, and the file list box - to display the system's drives, directories, and files , all with

1~ a few mouse clicks or keystrokes. This chapter explains the file-system controls and shows
you how to use them so users can investigate, and choose, among available disk files in your
applications.
The main sections in this chapter are:
• Examining the File System
• The Launch Pad Application
• A File + Open Dialog Box
• Other Ways of Using File-System Controls
296 Part 4 Advanced Applications

Examining the File System


The tool s you use to draw the file- system controls are at the bottom of the Visual Basic
Toolbox , as shown in Figure 20.1 .

~ - OrWe hst box

~ - File /Jst box

1 Direc torv list box


Figure 20.1 The tools far the file-system controls

Each of th e co ntrol s - th e drive li st box , the directory li st bo x. and th e fil e lis t bo x - have
been carefully designed to combine flexible and sophi sticated file-system inspection
capabilities with easy programming. Figure 20.2 shows the three co ntrols used together.

= calendar. exe
Forml
. li;;:Jc: [DISK) ªª
w- r- Orive list box
cardlile. exe
clipbrd. exe
clock.exe
control.exe
--E:}c: \

L]
..
games
icondraw.exe L] icons
msdos. exe L] system
pbrush. exe
L] winstuff
pifedit. exe •

1
1 File list box Directory list box
Figure 20.2 The file-system controls in action

The controls themselves obtain all the information they display frorn th e operat ing system;
you can access this information through their properties . You can use the co ntrol s
indi viduall y, or combi ne them in different ways by programming their interactions. For
example, you can display a list of the files in the current working directory with names
matchin g the pattern *.FRM. Just draw the Filel control on the forrn , th e n set its Pattern
property , either by typing *.FRM in the Properties bar, or by using thi s code at run time:
Filel.Pattern = "*.FRM"

The Orive List Box


The drive list box is a drop-down list box. In its normal state, it display s th e c urrent drive on
the user's system. When the user clicks the arrow at the right of the drive li st box , it drops
down to li st all valid drives. The user can select from that li st to change the c urrent dri ve.
You use the Drive property of the drive li st box to return or se t the current dri ve at run tim e .
T he Drive property is not available at design time.

"v1ic ros oft Visual Basic Programme r's Guide


Chapter 20 Using the File-System Controls 297

The Directory List Box


The directory list box displays the directory structure of the current drive on the user' s
system, beginning with the top-level directory. The current directory appears as a shaded,
open file folder; directories above it in the hierarchy appear as nonshaded open file folders;
and directories immediately beneath the current directory are shown as closed file folders .
Y ou use the Path property of the directory list box to retum or set the current directory at run
time (Path isn't available at design time). For example, you may want a directory list box to
display the files in the current directory of the drive displayed in a drive list box. To do so,
assign the Drive property of the drive list box to the Path property of the directory list box .

The File List Box


The file list box displays files contained in the current directory . The files shown in a file li st
box are those in the directory specified for its Path property (which is not available at design
time). A subset of these files can be displayed by setting the Pattem property-for example,
* .FRM displays only files with that extension.

Using the Controls Together


If you use a combination of file-system controls, you can synchronize the information they
display. For exarnple, if you have a drive list box, directory list box, and file list box with
default names Drive 1, Dirl, and File 1, the sequence of events might work like this:
l. The user selects a drive in the Drivel list box .
2. A Drivel_Change event is generated, and the display in Drivel is updated to reflect the
new drive.
3. To synchronize the Dirl list box with the Drivel control , the Drivel _Change procedure
passes on the new selection (the Drivel.Drive property) by assigning it to the Path
property of the Dir 1 list box.
4. The assignment to the Path property then generates a Dirl_Change event, and updates
the display in Dirl to reflect the current directory of the new drive.
S. To synchronize the Filel list box with the other two controls, the Dirl_Change event
procedure then passes on the new selection (the Dirl .Path property) by assigning it to the
Filel.Path property of the Filel list box.
6. The assignment to the Filel.Path property then causes the display in the Filel list box to
reflect the Dirl path specification.

Which event procedures you use or which properties you change depends on the way your
application is using the combination of controls . The next section illustrates one combination
that launches applications.
For more information on file-system controls, see the Language Reference, or:

Search Help for:


ID file system

Microsoft Visual Basic Programmer's Guide


298 Part 4 Advanced Applications

The Launch Pad Application


Most applications provide substantial capabilities for investigating the file system, since it' s
often desirable for the user to quickly find any file or group of files available to an
application. The Launch Pad application presented in this section uses file-system controls to
enable applications to be started from anywhere in the system.
The Launch Pad is somewhat faster than the File Manager because it does not maintain all
the information about a disk for future reference. lts display is restricted to files with the
EXE extension (by the Filel.Pattem property listed above), but you also can easily add
option buttons to perrnit display of .COM and .BA T files.
To start creating Launch Pad, create a new form and set its Caption property to "Launch
Pad." Then create the controls shown in the following table so that they resemble those in
Figure 20.3, and enter the code listed in the rest of this section . When you are finished , you
should have a working Launch Pad.
Control Property settings Significant events
Drive list box CtlName = Drivel Change
Directory list box CtlN ame= Dirl Change, Click
File list box CtlName = Filel , Click, Db!Click
Pattem = *.EXE
Frame CtlName = Framel ,
Caption = Run
Command button CtlName = Button, Click
Caption = &Maximized,
Index = O
Command button CtlName = Button , Click
Caption = M&inirnized,
Index = 1
Command button Ct!Name = Button, Click
Caption = &Normal,
Default = True, Index =2
Command button Ct!Name = Button, Click
Caption = E&xit,
Index = 3

Mic rosoft Visual Basic Programmer's Guide


Chapter 20 Using the File-System Controls 299

Note that in the drive list box a Change event is triggered by a single mouse click on an
item, but in the directory list box a double-click is necessary to generate the Change event.
(In the drive list box a Change event also results from selecting an item, then changing the
focus on the form.) In both the directory and file list boxes, the single click just selects
(highlights) the item, rather than choosing it.

= Launch Pad aa
calendar.exe
cardlile.exe
• li;;Jc:
E':>c:\
[DISK) w
clipbrd.exe
clock. exe L) games
control.exe L) icono
msdos.exe
notepad. exe L) system
pbrush.exe L) winstuff
piledilexe
omcao. exe •

Aun calc. exe LJ


1Maximized 11 Minimized 11 Normal 1 ~

Figure 20.3 The Launch Pad Application

Note You should draw the frame control befare you draw the first three command buttons
inside it. Also, the file-system controls do not have caption properties, although you can use
labels to name them and give them access keys. (For more information on using labels this
way, see "Shortcut and Access Keys" in Chapter 10, "Responding to Commands.") The
captions used for the frame and command buttons include ampersands to give them access
keys.

Writing Code for Launch Pad


O~e you have created the Launch Pad form and drawn the controls, start writing the code
by placing these definitions in the Declarations section of the form:
Const FILEBOXCLICK - 0, DIRSBOXCLICK - 1
Dim LastChange As Integer

The variable LastChange contains a value associated with the symbolic constant
FIL EBO XC L I CK or DI RS BOX CLIC K. Under certain circumstances one of these values is
assigned to Las t Ch an ge to help track what the user is doing. For example, in the procedure
Dirl_Click, Las te ha nge is set to DI RSBO Xe LI e K.

Microsoft Visual Basic Programmer's Guide


300 Part 4 Advanced Appl ication s

Launch Pad uses the procedures shown in the following table to handle the significant
events.
Procedure Description
Dri ve l _Change The Change event is generated when the user clicks a dri ve
specification . The Change procedure assigns the new drive
info rmation to the Dirl.Path property. This assignment
triggers a Change event in the Dirl control, forcing it to
update its di splay.
Di r l _C hange If the user double-clicks a directory name, the di splay is
updated and the Change event is generated . Thi s procedure
passes on the new path information and resets the focu s to
the File l control , fo rcing a di splay update anda Change
e\·ent in the File l list box.
Dir l_Cl ick If the u ser clicks a directory name, the DIR S BOXC LI CK
value is assigned to the variable LastChang.áf thi s is stil l
the value of LastChange when a command button is
chosen, the directory and fil e-system controls are updated.
F iJ e l _Click T he Click procedure resets the Caption property of the
frame around the command buttons to reflect the name of
the program the u ser clicked. It also assigns FI LEB OXCLI CK
to Last Change.
F ile I_DblC li ck A double-click meaos the user has made a fin al choi ce, so
this procedure calls the Button_Click event procedure and
passes the index of th e defa ult co mmand butto n to ini tiate
the program.
Button_ Cl ick Checks what the last change was before the user chose th e
defau lt command button. If the las t change was not in the
Dri ve l or Dirl box, the drive and path are reset at the DOS
leve!, then the fil ename is passed to the Shell functi on to run
the program .

The Drivel_Change Procedure


Whe n the user clicks an item in the Drive l box, its Change event is generated, and th e
Oriv e I Change C \-C nt rrnccclurc i, invoked. Enter thi s codc for that proccd ure :
Sub Drivel _Change ()
Thi s e vent was triggered by a chan ge in the Ori ves box .
' The change could have been eit her a mou se c l ick or movin g
' the highlight usi ng the keyboard , th en changi ng focus.
Dirl.Path = Drivel.Drive ' I f new dr i ve was chose n , thi s cau ses
' t he Dirl box to upd ate its di s pla y.
End Sub

Microsoft Visu al Basic Programmer's Guide


Chapter 20 Using the File-System Controls 301

The preceding code assigns the u ser' s choice to the Path property for Dir 1, changing the
Dir l display to show the files in the current directory on the new drive. This assignment also
triggers the Dirl_Change event. Note that the Change event in a Orive list box occurs when
a new drive is chosen, either with a single mouse click, or when the user moves the selection
(for example, with an arrow key), then changes the focus .

The Dir1_Change Procedure


If the user double-clicks an item in the Dirl list box, or if the Path property of Dir 1 is
changed in code (as in the Drivel_Change procedure), the Dirl_Change event is initiated.
Enter this code to respond to that event:
Sub Dirl _ Change ()
Filel . Path - Dirl.Path ' Synchronize both paths.
Filel.SetFocus ' Move focu s to Filel box.
' If there are items in the Filel list box, select the first
' it em; otherwise. reset frame caption. •
If Filel.ListCount Then
Filel.Listlndex - 0
Else
Framel.Caption = "Run"
End I f
End Sub

The second line of the procedure assigns the Path property of the Dirl box to the Path
property of the Filel box. This causes a change event in the Fi le ] control, which is redrawn .
However, you don't need to .add code to the Filel_Change procedure, because for this
application , no event chain continues after changes to the File l box have been made .

The Dir1_Click Procedure


A simple Click in the Dirl box does not cause a Change event. If it did, the box would
update itself to display the directory just selected. This would make it impossible for a user
to use the arrow keys to move through the list in the box. Using the arrow keys is equivalent
to a single click, so in the Dir 1_ Click procedure the Las t Ch an ge flag is set to reflect that
the user moved the Dirl selection, but did not actually choose a new directory. No action is
taken to update the Dirl or Filel boxes unless Las tC han ge equals OI RSBOX CLIC Kwhen a
command button is chosen.
E11tc1 this codc to rc~pond to a single cl ick :
Sub Dirl _ Click ()
· If the user clicks a directory just note the fact in LastChange.
• A sin gle click does not trigger a change event in a Dirl list box.
LastChange - DIRSBOXCLICK
En d Sub

Microsoft Visu al Basic Programmer's Guide


302 Part 4 Advanced Applications

The File1 Click Procedure


Enter this code to be invoked when a user clicks an ítem in the Filel list box:
Sub Filel_Click ()
' Note a simple click in the File control does not trigger a
' change event, only a click event.
Framel.caption - "&Run "+ Filel.FileName ' Show application to be run .
LastChange - FILEBOXCLICK ' Set flag for button press .
End Sub

The frame's caption is set to reflect the name of the chosen program, and the constant
FI LEBOXCLICK is assigned to LastChange Remember, a Change event is not initiated by
a si ngle click in either Dirl or File 1, although the change event is triggered by a single click
in Drivel.
The File1 DblClick Procedure
Although you don ' t add code to the Filel _Change procedure, it is necessary to add the
following code to File l _DblClick: .
Sub Filel_DblCli ck ()
' If the user double -clicks a filename, choose the default command button
' so the application will start Maximized.
Button_Click (0) ' Pass the default index value.
End Sub

The single line of code in this procedure sim ulates choosing the default command button ,
which is named Button(O) and labeled Run Maximized .

The Button Click Procedure


As you might expect, most of the code in the Button_Click procedure deals with actually
launching the chosen application. However, a check is first made to be sure the last action
the user took was not moving the selection in the Dirl list box. This check is necessary,
because a user may not be using a mouse; it's common practice to use the arrow keys to
move among items in a list box, and then press ENTER to actually choose one ítem. Becau se
the ENTER key is associated with the default command button , the Button_Click procedure
must rule out the possibility that the u ser is just trying to set a new driv e.

Microsoft Visual Basic Programmer's Guide


Chapter 20 Using the File-System Controls 303

Enter this code for the Button_Click procedure:


Sub Button_Click (Index As Integer)
' This procedure handles choosing a command button. If the index
' is>- 3 (Exit - 3). the application ends. Because a user may press
' Enter to complete the choice of a new directory, the LastChange
' flag is examined first to see if the user is trying to move
· to a new directory. If so, the Dirl box Path property is updated.
' If LastChange was not in the Dirl list box. the drive and path are
' set at the DOS l evel . Then the Shel l statement tri es to start the
• application represented by Filel . FileName . Whether the application
' begins as normal. minimized. or maximized is determined by the second
' argument (3 - Index) to Shell . Finally, LastChange is reset.
If Index >- 3 Then End ' End on Exit button press.
But t on(0). Set Focus ' Pu t focus on Run Maximized.
If LastChange - DIRSBOXCLICK Then
Dirl.Path = Dirl.List(Dirl.Li stlnde x ) ' Update the Dirl list box.
Else
If Fil el . Fi l eName <> "" Then
' Changing the drive and dir ectory at the operating system level
• ensures that an application t hat needs another file (such as a DLL)
' will run properly if the ot her file i s present in the application's
' directory .
ChDrive Drivel.Drive ' Chang e to drive shown in Drivel box.
ChDir Filel.Path ' Change to directory in Dirl box .
If Shell(Filel.FileName. 3 - Index) < 32 Then
Msg$ - "Couldn't run app l i cat io n. So rry!"
Ms gBo x Ms g$, 1, "Error starting ap pl i cati on"
End I f
Else
Msg$ = "Sorry! You must fi rst se l ec t an application in the list box."
MsgBo x Msg$, l. "No appli cation chose n."
Filel . SetFocus
End I f
End If
LastChange - FILEBOXCLICK ' Reset th e flag .
End Sub

Microsoft Visual Basic Programmer's Guide


304 Part 4 Advanced Applications

lf the user is indeed tryin g to launch the application, a check is made to be sure there is a
filename selected in the File] box by examining the Filel.FileName property . Then the drive
and path are updated at the DOS level. The Shell function starts the application represented
by the first argument, File] .FileName. The second argument describes how the application
should be displayed: Normal (1), Minimized (2), Maximized (3), and so on. The indexes for
the command buttons are chosen so that subtracting them from 3 produces the appropriate
argument-for instance, 3 minus the index of 1 for the command button labeled Minimized
produces the argument of 2.

Delayed Error Trapping


The chance for an error in Launch Pad is remote because everything displayed by the file-
system controls is a valid part of the system. However, a removable-media drive door could
be left open , a network drive could disconnect, or sorne other access problem could cause an
error. lf a user selec ts that unavailable drive in the Drivel list box, the attempt to access it
fails. But the Drivel.Drive property remains set to that device, because it is a click that sets
the value. Toen when the attempt is made to assign the selected drive to Dirl.Path, an error
is generated.
You can rewrite the DriveJ _Change procedure to handle those eventualities:
Sub Drivel _Change ( )
' This event was triggered by a change in the Drivel box.
' The change could hav e been either a mouse click or moving
' the selection us i ng the keyboard, then changing focus.
On Error Resume Nex t ' Delay error handling.
Dirl.Path - Dr i ve l . Dri ve ' If new drive wa s chosen. this causes
' the Dirl box to update itself.
If Err Then ' If an error occurred, tell us er what
MsgBox Error$ ' it was, then reset Drivel . Drive.
Drivel.Drive Dirl .Path Dirl.Path was not changed, therefore it
End I f ' still has old drive spec.
End Sub

When you handl e errors thi s way, you assume one solution for any possible error. You can
combine thi s with the error-handling techniques discussed in Chapter 19, "Handling Run -
Time Errors," to make it more foolproof.
Now that you 've entered the code, press FS to run Launch Pad. You should be able to use it
to start appli cation s ju st as you do from the File Manager.

Microsoft Visual Basic Programmer's Guide


Chapter 20 Using the File-System Controls 305

A File+ Open Dialog Box


The Launch Pad application illustrates the ease with which you can create forrns that enable
the user to search the file system for desired files. In this section, you'II create a dialog box
to enable any of your applications to retrieve file-specification inforrnation from a user. The
Filelnfo dialog box, shown in Figure 20.4, uses the same file-system controls as Launch Pad,
but combines them with a text box so that the user can directly type a filename , or specify
different patterns or paths.

= Filelnfo
OK Cancel
ªª
c:\winword
a rti el e . dot • 1o c:\
basic.dot !2::7winword
brief.dot L] winword.cbt
brochdat.dot
brochmrg.dot
brochure.dot
contract.dot
conv-wrd.dll
conv-wri.dll
conv-ww .dll • !IEJc: [DISK) w
Figure 20.4 The Filelnfo Dia log Box

Start building Filelnfo by creating a new form and setting the forrn ' s FormName and
Caption property to "Filelnfo." The following table summarizes the controls, properties to
set, and significant events for the application.
Control Property settings Significant events
Textbox CtlName = TextBox Change
Label CtlName = PathSpec
Orive list box CtlName = DriveDropDown Change
File list box CtlName = FileListBox Click, Db!Click,
PatternChange, PathChange
Directory CtlName = DirsBox Change, Click
Command button CtlName = DlgButton(0), Click
Caption = OK,
Default = True
Command button CtlName = DlgButton(l), Click
Caption = Cancel

Microsoft Visual Basic Programmer's Guide


306 Part 4 Advanced Applicatio ns

Filelnfo uses the procedures shown in the following table to handle the significant events of
th e control s.
Procedure Description
Form_ Load Initializes the dialog box. Places a default filename (or
matching pattem) in TextBox, as well as a drive and path
specification in the DriveDropDown and DirsBox boxes.
FileListBox_PathChange If the Path property in FileListBox is altered, this procedure
initiates synchronizing of the information in the other
controls (both the DriveDropDown and DirsBox list boxes
and the PathSpec label).
TextBox_Change Assigns TEXTB0XCHANGE to LastChang e.
Drive DropDo wn_ Ch ange If a new drive is elected from Dri veDro pDown (e ither by
the user clicking the control or from code) , assigns the new
drive to the DirsBox.Path property to update DirsBox.
DirsBox_Click Assigns DIR SB0XCLICK to the variable La s tChange to
indicate DirsBox was the last one changed.

DirsBox_Chan ge If a different directory is chosen (either by the user double-


clicking the control or from code), assigns the new
DirsBox. Path property to the FileListBox.Path property so
that FileLis tBox is updated. Also updates the PathSpec
label.
Fil eListB ox_ Click If a filename is selected from FileListBox , places the
selec ti on into TextBox. Note thi s tri ggers a TcxtBox C han ge
event.
FileListBox_DblClick The DblClick event is generated when th e user chooses a
filename.
DlgButton_Click If the OK button (lndex = O) is chosen , the variab le
LastC hange is checked to see which contro l was last
modified. If it was the text box, the new TextBox .Text is
assigned to the FileListBox.FileName. 1f the last change was
a Click in the DirsBox, the selection is ass igned to
DirsBox.Path.
If the Cancel butto n (lndex = 1) is chosen , the fo rm is
unloaded and none of the global variables is modified .

Microsoft Visual Basic Programmer's Guide


Chapter 20 Using the File-System Controls 307

Note that in the Launch Pad application, the code to launch the application appears in the
Button_Click procedure, and the lndex property of the button chosen determines whether the
program starts in maximized, minimized, or normal size. This dialog box is slightly
different. The command buttons here indicate only whether or not the user has chosen a
filename:
• If the Cancel button is chosen, the dialog is cancelled and no information is made
available to the application.
• If the OK button is chosen, the global variables containing the filename and path are
modified. This is carried out in the file control' s DblClick procedure, rather than in the
button' s Click procedure, so the code appears only once.

Writing Code for the Filelnfo Dialog Box


Start entering the code for Filelnfo by placing these declarations in the global module:
Global TheFileName As String ' Used to pass user choice of filena me from
' Filei nfo to other parts of appl ication .
Global TheNewPath As String ' Used to pass path information from
' Fileinfo to other parts of application.
Global FileinfoTitle As String ' Dialog box title.

When you want to use the dialog box in an application, merge the global module of the
Filelnfo project with the global module of the application from which you intend to display
the dialog box.
Define the following in the Filelnfo form-leve l Declarations section :
' Code indicating where the la s t s ignificant event took
' place befare the user chose th e OK button.
Dim LastChange As Integer

' Symbolic constants to represent possible LastChange value s .


Const TEXTBOXC HANGE = 1, DIRSBOXCLICK = 2

The Filelnfo example assumes the following Show method has been executed, and it starts
with the Form_Load procedure:
Filelnfo . Show MODAL

The argument MODAL is defined in the file CONST ANT.TXT. The constants TRUE and
FALSE also are defined in CONSTANT.TXT, and are necessary for Filelnfo to work
properly. Merge CONST ANT.TXT with your global module. Information exchan ged
between the form and the application using it is placed in global variables - in this case, the
global string variables TheNewPath and TheFi l eName. Information about the user's choice
is assigned to these variables in the FileListBox_DblClick procedure. Once the Fi lelnfo form
is hidden or unloaded the Filelnfo dialog information in TheNewPath and TheFi l eName
can be used by the app lication.

Microsoft Visual Basic Programmer's Guide


308 Part 4 Advanc ed Appli cations

The Form Load Procedure


The Filelnfo dialog example is more ambitious than Launch Pad because it enables the user
to type information directly into a text box . But if the user types in invalid information (such
as specifying a pattem or path with an illegal character), an error may be generated .
Simi larly, in Form_Load, the path is checked to see if it ends in a backslash before
attempting to assign it to the FileListBox.Path property. If it does , the backslash is removed .
Enter thi s code for the Form_Load procedure:
Sub Form_ Load ()
' Be ca use this form may be loaded several times during the run of an
application, the values of TheNewPath and TheFileName are checked
' so bro wsing begins at the place previously chosen by the user.
Filelnfo.Caption = FilelnfoTitle

If TheNe wPath <> "" Then


' l f TheNewPath end~ with a backslash, remove it.
I f Rig ht$( TheNewPath, 1) = "\" Th.en
TheNe wPa th = Left$(TheNewPath, (Len(TheNewPath) - 1))
End I f
' If TheNewPath isn't the path, make it the path. Note that
' such a chang e triggers the FilelistBox_ PatternChange event .
lf TheNewPath <> FilelistBox.Path Then
Fi l el i stBox.path = TheNewPat h
End I f
End I f

' If the globa l variable TheF ileName is not null. check item s in the lis~
' box to see if it is in the re . If so , put it in the text box.
I f TheFi l eName <> '"' Then
Far Ind% = 0 To FileListBox.ListCount
If Fileli stBox.List(ind) = TheFileName Then
TextBox.Tex t = TheFi leName
Exit Far
End I f
Next Ind%
End I f

PathSpec.Caption = DirsBox.Path ' Su mmari ze information far user.


lf Filel i stBox.Listlndex = - 1 Then
TextBox .Text = FilelistBox .Pattern lf nothing i s showing in the
End I f list box, put the pattern i n
TextBox.Se l Start = 0 ' the text box, then select the
TextBox.Sellength = Len(TextBox.Te xt) ' text in the text box .
End Sub

Microsoft Visual Basic Programmer's Guide


Chapter 20 Using the File-System Contra Is 309

The FilelistBox_PathChange Procedure


Remember, Visual Basic controls are more than just pictures on the screen. They also
represent code that performs specific actions in response to events, and they trigger new
events for which you can write response code. As with Launch Pad, all the Filelnfo dialog
box controls can be made to respond to each other with just a few lines of code, making it
very easy for the user to navigate through drives and directories looking for specific files.
In the Form_Load procedure, if T he New Pa t h is assigned to FileListBox.Path, the
FileListBox_PathChange event is triggered . Enter this procedure to respond to that event:
Sub FilelistBo x_PathChange ()
' Change DirsBox.Path and DriveDropDown.Dri ve to reflect
' the new path.
DirsBox.Path - FilelistBox.Path
DriveDropOown. Dri ve = Fi l e Li stBox. pa t h
End Sub

The TextBox_Change Procedure


Similarly, if the Form_Load proced ure assig ns TheFi l eName to the Text property for
TextBox, a TextBox_Change even t occurs. Although a change event is generated whenever
there is an ass ignment to the text box, it is only of interest if it's the last event prior to the
user choosing the OK button. Therefore, handling the TextBox_Change event consists only
of setting the form-level variable Las tC han ge to a value that represents the TextBox (in
this case 1, represented by the constant TEXTBOXCHANGE):
Sub TextBox_Change ()
LastChange = TEXTBOXCHANG E
End Sub

The DriveDropDown_Change Procedure


If a user chooses a new drive in DriveDropDown, Filelnfo responds to the
DriveDropDown_Change event with the following codeso that the DirsBox con tro l is
updated:
Sub DriveDropDown _Change ()
On Error Resume Next ' Delay error handling .
DirsBox.Path = DriveDropDown . Drive
' If new drive was cho s en, thi s causes the Dirs bo x to update itself.
If Err Then · If an error occurred. tell user what
MsgBox (Error$) ' it was, then reset Drivel.Drive .
' DirsBox.Path was not changed. therefore it still has old drive sp ec.
DriveDropDown.Drive = OirsBox.Path
End I f
End Su b

Microsoft Visual Basic Programmer's Guide


310 Part 4 Advanced Appl ication s

As with Launch Pad, ass igning the new drive name to DirsBox.Path causes the contents of
the DirsBox control to change, reflectin g the current directory on the new drive. This in turn
tri ggers the DirsBox_Change event. The only events you must respond to in the
DriveDropDown control are the Change events. A Click event is equivalent to choosing the
item (rather than just selecting it) .

The DirsBox_Click Procedure


Enter this code for the Click event:
Sub Dir sBox_Click ( )
LastChange = DIRSBO XC LI CK
End Sub

A Click event in th e DirsBox control means the user has selected, but not chosen, a new
directory . This may be a result of ei ther clicking a mouse in the box or pressing an arrow key
while the box has the focus. Rather than responding by refilling the related list boxes, just
note in the DirsBox_Click procedure that this was the user's last action. No Change event is
triggered by a click in the DirsBox control.

The DirsBox_Change Procedure


If the user immediately follows the click by choosing OK, then you can treat the
combination of events the way you would a Change event. Note that the Change event also
can be tri ggered by double-clicking the DirsBox control. You then handle the
DirsBox_C hange event with this procedure :
Sub Dir sBox_Chang e ()
Path Spec.Caption Dir s Box.Pat h
File l i s tBox.Path = DirsBox . Path
End Sub

The assignment to PathSpec.Caption causes the current path information to be di splayed


beneath the text box control. Because this display is its only task, you don ' t need to handle
any !abe! events. But when th e Path property for DirsBox is assigned to FileListBox.Path,
the contents of FileListBox are automatic all y updated to reflect the new path . With just a
few lines of code, you 've set up an event sequ ence that keeps the controls synchroni zed
every time a change is initiated .

Microsoft Visual Basic Programmer's Guide


Chapter 20 Using the File-System Controls 311

The FilelistBox_Click Procedure


For the FileListBox control, you need code to respond to the Click (which selects a
filename), DblClick (which chooses the filename), and PathChange events as well. If the
user selects a filename in the FileListBox control (by clicking it or selecting it with the
arrow keys), the FileListBox_Click procedure can display the user's choice in the text box
with this event procedure:
Sub FilelistBox_Click ()
TextBox .Text = FilelistBox.FileName
End Sub

The FilelistBox_DblClick Procedure


If the user actually chooses a filename in the FileListBox control (by double-clicking it , or
by selecting it and then pressing ENTER), it meaos the user has made a final choice of
filename and path, which is the reason you displayed the dialog box in the first place.
Therefore, your FileListBox_DblClick procedure can gather the inforrnation, assign it to
global variables for safekeeping, then hide the forro:
Sub FilelistBox_DblClick ()
' When user double-clicks the file list box, it means the soug ht -
, after file ha s been found. Assign the current path to the global variable
' then make sure it has a backslash in it. Assign the chosen filename
' to the global variable TheFileName.
TheNewPath = DirsBox.path
If Right$(TheNewPath, 1) <> "\" Then TheNewPath - TheNewPath + "\"
TheFileName = TextBox.Text
FilelistBox.Pattern = * * ' Reset the list box pattern .
Filelnfo . Hide ' Hide the form so it will appear
' quickly when needed again.
End Sub

The DlgButton_Click Procedure


When the user chooses a command button, you first check the variablelastChange to see
whether the last action was selecting a new directory or typing in the text box. If the last
action was selecting a new directory, you assign the selection to DirsBox.Path, which
triggers the DirsBox_Change event, whose event procedure then updates FileListBox_Path,
which refills the list box according to the current matching pattem.

Microsoft Visual Basic Programmer's Guide


3"12 Part 4 Advanc ed Applications

If the last action was a change in the TextBox control, the code examines the contents of the
box to see whether the user simpl y typed a filename, typed in new drive or path or pattern
specifications, and so on .
Note th at if a strin g assigned to FileListBox.Filename contains wildcard charac ters, no
Db!Click event occurs, but the stri ng becomes the FileListBox.Pattern. A filename with no
wildcards is also a valid pattern , and it also changes the pattern property, and th e only item
in tne li st box becomes the matching filename. Finally, the fact that the ass igned string
represented a filename in the box triggers a FileListBox_Db!Click event. The code below
handl es the possibilities . Then thé new text is selected in the text box, it receives the focus ,
and the Yariable LastChange is reset to O:
Sub DlgButton_Click (Index As Integer)
' Index tells whether DK or Cance l wa s cho sen. This procedur e checks
' wh ere the last change occurred . If i t was in the text box , the code
determines whether a valid filename now appears there . If so , that
' name i s assigned to FilelistBox.FileName. If not. the code c he cks to
' see if a new pattern was ente red , and pla ces it in FilelistBox.Pattern .
' If it wa s neither a valid filename nora val id pattern, the previous
' pattern is shown in the text box . If LastChan ge wa s DIRSBO XCLICK,
,· assigning t he clicked directory to Dir sBox.Pat h i nitiates events to
' update other pieces i n t he dialog.

If Index = 0 Then ' If user cho oses the OK button .. .


Select Case LastC hange
Case TEXTBOXCHANGE
When you assign to the Filename property, the
value i s checked. If it includes path information
t hen the drive and directory control path properti es
are updated and the box is updated. Whenever these
are updated, your code shou l d in turn update the
file list box control Path property, which would then
cause the list to be updated.
Fo r Ind % = 0 To Fil eListBox.ListCo unt
If FilelistBox.List(I nd %) = TextBox.Text Then
' When this assignment is made. it triggers
' the Fi leli s tB ox_Db l Cli ck event, and also
resets the FilelistBox.Pattern prop erty
to FilelistBox.Filename.
FilelistBox.Filename = TextBox.Text
Foundlt = TRUE
Exit For
End I f
Next I nd%

Mic rosoft Visual Basic Programmer's Guide


Chapter 20 Using the File-System Co ntro ls 313

If Foundlt <> TRUE Then


' Figure what user is trying to do.
ColonPos% = InStr(TextBox.Text. ": " )
BslashPos% - InStr(TextBox .Text. "\")
Sta rPos% = I nStr (TextBox. Text. "*")
OueryPos% - InStr(TextBox.Text. "?")
' If dri ve is to change. do it first.
If ColonPos% Then
DriveDropDown.Orive = Mid$(Text8ox.Text. ColonPos% - 1, 2)
End If
' See if the pat h is longer than the root ...
If BslashPos% Then
Test$= TextBox.Text
Do Until InStr(Test$. "\" ) = 0
LastOne% = InStr(Test$, "\")
Mid$(Test$, LastOne%. 1) = "/"
Loop
'If so. get path spec up to last one. otherwise leave ita s is.
If LastOne% > 3 Then
Path$ - Left$(Text8o x. Text. LastOne% - 1)
Else
Path$ - TextBox . Text
End If

OirsBox.Path = Path$ ' Reset the path in DirsBox.


End I f
' If there's a wildcard specification. handle that now.
If StarPos% Or OueryPo s% Then
a$=Text8ox.Text
FileListBox.Pattern = Right$(a$, Len(a$) -LastOne%)
Else
TextBox.Text = FileListBox.Pattern
End If
End If ' End of If Foundlt <> TRUE co ndition.
Case DIRSBOXCLICK
Dir s Box.Path = Di rsBox.List(DirsBo x .Listlndex)
End Selec t
' Highlight whatever appear s in the text box and. if the form is vi s ible.
· put the focus there .
TextBox.SelStart = 0
TextBox.Sellength = Len(TextBo x. Tex~)
If Vi sib le Then TextBox .SetFocus
Else ' If user is cancelling, set the globals to
TheNewPath ' null strings, then hide the dialog.
TheFileName =
Filelnfo . Hid e
End I f
End Sub

Microsoft Visua l Basic Programmer's Guide


314 Part 4 Advanced Applications

Ouerying and Setting the FileName Property


You've already seen that an assignment to DirsBox.Path triggers the DirsBox_Change event.
An assignment to FileListBox.FileName can have multiple effects, possibly triggering
FileListBox_DblClick, FileListBox_PathChange, and FileListBox_PattemChange events as
well. This section discusses these possibilities.
W-hen you query the FileName property, the filename of the currently selected file is
returned, without path information. However, when an assignment to the FileName property
occurs, the control actually examines the contents of the assigned string:
• If the string begins with a drive letter and a colon, or if it contains a backslash, the new
path information is assigned to the Path property and a PathChange event is generated.
• If the string contains a matching-pattem character (* or ?), the pattern is placed in the
Pattem property and the PatternChange event is generated.
• Altematively, if the string contains a valid filename in the current directory, the DblClick
event is generated. Assigning an illegal value to the FileName property of a file list box
(for exarnple, a null string) results in a run-time error.

The Pattern Property


The Pattem property in the FileListBox control enables you to display all files (*. *, the
default matching pattern) or a specified subset of the files in the path. Your code can assign
other values (*.TXT, NEW???.DOC, and so on.) to the FileListBox.Pattern property, or
respond to pattems entered by the user. If there are files that match the pattem, they are
displayed in FileListBox. If there is no match at all for a valid pattern, the box is emptied. If
the pattem is invalid (for example, if the pattem is a null string), a run-time error is
generated .

Other Ways of Using File-System Controls


The Filelnfo form can be modified to allow many types of disk-related activities. For
example, your application can modify the File + Open dialog to save files under new names
(File+ Save As). In other circumstances, you might want to use the individual controls to
determine system information without ever displaying them. To do this, you can set their
Visible property to False, then query and manipulate the controls to determine whether any
drive and directory combination contains a certain file or files .
You can add other controls and properties to the Filelnfo dialog box. For instance, you can
add a combo box to store matching patterns as the user works with the application. If the
user types in a matching pattem, your code can check the existing selections in the combo
box ; if the one the user typed is not among them, you can add it with the Addltem method.
Sometimes you may want to display only files with certain attributes. The file list box has
attribute properties (Normal, ReadOnly , Archive, Hidden, and System) you can set to True
or False, depending on whether yo u want that type of file to appear in the list box .
The next chapter, " Processing Files," builds on the information in this chapter by showing
yo u how to use the input and output features in Vi sual Basic to manage data in files.

Microsoft Visual Basic Programmer's Guide


Processing Files

Many of the applications you'll create with Visual Basic will need to write data to disk, read
data from disk, or both. In fact, many applications would be ali but useless if you could not
save the data you have entered, or read in old data to be displayed and modified.
This chapter presents two sample applications, Text Editor and Record Editor, to show you
how to use the file input and output (I/O) functions and statements in Visual Basic to access
data stored in files. It includes material on a variety of programming tasks related to
retrieving, storing, and formatting information .
The main sections in thi s chapter are:
• Working with Data Files
• Using Sequential Access for Text Files
• Records in Random-Access Files
• Binary File I/O

oft QuickBasic file-access methods, much of the


ady be very fami liar. Any fii e-access code used in
ºthin Visual Basic. However, in the Microsoft
rating env ironments, COM ports may be more
with Visual Basic statements. Similarly,
in Visual Basic with the Printer object and
a chann el to a printer.
316 Part 4 Advanced Applications

Working with Data Files


The term data describes any information needed, generated, or manipulated by a program .
Data files are phys ical locations on your disk where information can be stored. The
following tasks are greatly simplified by using data files in your Visual Basic application s:
• Creating, manipulating, and storing large amounts of data
• Accessing severa! sets of data w ith one application
• Using the same set of data in severa] different applications

The sections th at fo llow introduce the concepts of records and fields, and contrast different
ways to access data files from Visual Basic. They show yo u how to :
• Create new data fil es.
• Open ex istin g fil es and read their co nte nts.
• Add new info rmation to an existing data fil e.
• Change the contents of an existing data fil e.

Types of File Access


There are essentially three types of file access, each of which has advantages in different
situations. The following table lists the access types, the types of files for which each is
primarily used, and the statements typically associated with each type of access.
Access type Primary use Typical statements
Sequential Pl ai n te xt file s Open , Line Input#, Print
# , Input$, Close
Record files w hose reco rds vary in length Input#, Write #
Random Record files containing fixed-length Type ... End Type, Open ,
records Put, Len, Close, Get ,
Binary Every thin g else (a file is treated as a Open, Close, Seek, Input$
sequ ence of indi vidual bytes)

Ali types of fil e access use the FreeFile , EOF, and LOF function s to determine an available
fil e number, the end of a file, and its length, respectively. Also, you can use statements such
as Seek, Get, Put, and Input$ with file types other than those with whi ch they are normall y
used . The keywords are simply gro uped with th e access type with which they are most
commonly associated.
Sequen ria/ access assumes the fil e is a plain teitt fil e (o ne whi ch, if viewed with the DOS
TYPE comma nd, always appears as normal tex t). Each byte is ass umed to representa
character. Numbers in a file created with sequ e ntial access are represented by character
strin gs, j ustas wo rd s are. Sequential access makes it easy toread and modify the kinds of
file s produced with a text editordvbpgapafiles in which th e data is ,w t divided into a seri es
of individual record s.

Micros oft Visual Basic Programmer 's Cuide


Chapter 21 Processing Files 317

In a random-access file, string data also appears as normal text when viewed with the TYPE
command. But numbers are stored in binary format, rather than as strings of characters, so
there is no obvious relationship between the actual number and a number displayed with the
DOS TYPE command. Random access makes it easy to work with files whose data is
organized into man y discrete records, each of which has the same form and length, but each
of which contains individualized data.
Binary access uses statements similar to random and sequential access, but makes no
assumptions about what the individual bytes representdvbpgapathey could represent
anything from ASCII text to a series of records, or even the executable image of a program.
Although you can use sequential access to work with record-oriented files , random access is
simpler for that purpose, and more efficient. Although not commonly used now, Write # and
Input # were once used for record-oriented file access before Basic supported random file
access. These statements are sti ll supported in Visual Basic and you mi ght find them useful
for working with record-oriented sequential files that use the comma character as a field
delimiter.

Overview of File Access


Though each file access technique is differcnt, each type uses a similar access process. You
always:
l . Open a file with the Open statement and assign ita number by which it is known while
you are using it. Depending on how you want to access the file, you can open it in one of
five modes: sequential Input, sequential Output , sequential Append, Random access,
and Binary access.
2. Copy ali or part of the data from the file to program variables.
With sequenti al access, you read data from the beginning of the file toward the end until
you have read the whole fil e, or found the data you want. Random access all ows you to
access any specific record in the file by number. Using binary access, you can access any
individual byte position within the file .
3. Use, manipulate, or alter the data in the program variables.
4. Change the contents of the fil e by either overwriting the whole file with new or modified
data, or selectively changing specific portions of the file. When you use sequential
access, you usually overwrite the whole file at once, or append new blocks of text to the
end of it. With random access, the unit of change is usually a specific record at a specific
position in the file. With binary access, you usually change individual bytes within the
file , one at a time.
5. Use a Close statem ent to termínate access when you finish working with the file (or want
to change the access mode you are using with a sequential file). Specifying a number
with the Close statement doses only the file associated with that number. Close with no
argument doses ali files opened by the program. ·

Thi s chapter concentra tes on using sequen tia! access for the kinds of text files normally
produced by text edi tors. Random access is illustrated using the types of structured data you
mi ght find in a database . Binary access is only briefly summarized .

Microsoft Visual Basic Programmer's Guide


318 Part 4 Advan ced Appli cations

Note With the exception of sequential Output and Append modes, you can simultaneously
open the same file multiple times in the various modes . If a file is opened for any other
mode, it cannot be simultaneously opened for sequential Output or Append. When opened
for Output or Append, it cannot be simultaneously opened in Input, Random , or Binary
mode. All other combinations of simultaneous file opening are permitted.
If the same fil e is opened simultaneously under different file numbers, Visual Basic
independently tracks such things as file position for each file number. Y ou must use caution
under these circumstances, however, since different buffering of the same file opened in
different modes can foster inconsistent images of the file' s contents if both reading and
writing operations are being performed ..

The Open Statement


The Open statement has this syntax :
Open.file$ [For mode] [Access access] [lock] As [#]filenumbero/o [Len= recordLeno/o]

The argumentfile$ is a string expression specifying the file to open. It follows the operating
environment rules for naming and specifying files . It can therefore contain an optional drive,
as well as a complete, partial, or relative path specification. The mode is one of the fi ve
modes previously mentioned.
The filenumber is an integer identifier between 1 and 255, inclusive. lt is used by subsequent
file I/0 statements in the application as a shorthand way to refer to the fil e. As long as th e
file is open, this number remains associated with the file . When the file is closed, th e fil e
number is freed for use with another file. Your Visual Basic applications can open more th an
one file at a tim e. Use the FreeFile function to retrieve valid fil e numbers.
For informa ti on on the other arguments used in the Open statement, see th e Language
Reference, or:

m Search Help for:


open

The Fileüpener Function procedure illustrates the syntax of the Open statement used for ali
three sequ ential modes, as well as random and binary access. It accepts a filename and a
code representing the mode in which the file is to be opened. Fileüpener also accepts an
integer representing the length of a single record if the file is to be opened for random
access. It uses FreeFile to obtain a file number. If it succeeds in opening the fil e, Fileüpener
returns the fil e number to use in subsequent references to the file. Fileüpener also uses th e
FileErrors Function procedure outlined in Chapter 19, "Handling Run -Time Errors."
Note that the constan ts READ FILE , REP LACE FIL E, ADOTO FIL E, RAN DOM FILE, and
BINA RY FI LE are defined here as local constants. If their scope is greater in yo ur programs
(that is, if yo u defin e them globaily or at the module leve!), the local definitions should be
removed .

Microsoft Visual Basic Programm er's Guide


Chapter 21 Processing Files 319

Function FileOpener (NameToUse$, Mode%, RecordLen%) As Integer


' Opens a file in specified access mode.
' Arguments : NameToUse$ String representing a val id OS filename.
Mode% Integer representing file - access mode .
RecordLen% Integer specifying length of one record.
' Returns: Integer by which the file can be specified in the
program; return is zero if Open fails.
Const REPLACEFILE = 1, READFILE - 2, ADDTOFILE - 3
Const RANDOMFILE = 4, BINARYFILE = 5
FileNum% = FreeFile ' Get the integer identifier from OS .
On Error GoTo OpenerError ' Prepare far possible error.
Se lect Case Mode ' Select far user-specified access mode .
Case REPLACEFILE ' Sequential output.
Open NameToUse Far Output As FileNum%
Case READFILE ' Sequential input.
Open NameToUse Far Input As FileNum%
Case ADDTOFILE ' Sequential append.
Open NameToUse Far Append As FileNum%
Case RANDOMFILE ' Random access.
Open NameToUse Far Random As FileNum% Len= Record Len%
Case BINARYFI LE ' Binary access.
Open NameToUse Far Binary As FileNum%
Case Else
Exit Function
End Se lect
FileOpener = FileNum% ' Return the file number.
Exit Function
OpenerError:
Action% = Fi leError s(Err)
Select Case Action %
Case 0
Resume
· You needn't specify Case 1 or 2 since Case Else uses same response.
Case Else
FileOpener = 0 ' Tell ca ller Open failed.
Exit Function
End Select
End Function

Note the Len= clause in the Open statements. The default is 128 bytes for both random and
sequential access, but when opening a file for random access, Len must specify the exact
size of a single record . For sequential-access files you can use Len to specify how much of
the data file's contents are read into memory at once.

Microsoft Visual Basic Programmer's Guide


320 Part 4 Advanced App lication s

lf you increase thi s " buffer" size, large files are transferred faster between file and program
Yariabl es . Smaller values use less memory, but the transfer rate is slower. Len is ignored for
binary access, because the unit of tran sfer is always a single byte.

Using Sequential Access for Text Files


One of the exci ting features of Visual Basic is the ease with which you can create tool s such
as simple text editors. However, a text editor isn ' t very useful if you cannot save the tex t in a
di sk file between editing sessions. The easiest way to <leal with this type of file is sequen ti al
fi le access .
As shown in the preceding section, you use the Open statement to access fil es in Visual
Basic. With sequential access, a file is opened for only one operation at a time: either to read
it s contents. o ve rwrite its contents, orto appe nd new tex t to th e curren t contents. When an
operation fo r which it was opened is finished, the file is closed (using th e Close statement)
before being reopened for a different operation .
For exampl e, to ed it the text in a file, you can open the file using the Input mode, place the
current contents into a multiline text box, then clase the file . With the fil e' s contents in th e
te xt box, you can make any edits you wish, then open the file again in Output mode and
replace ali the old contents of the file with the modified text from the text box .

Note When you use sequential access to open a file toread from it, the fi le must already
exis t, ot herwise Visual Basic generates an error. However, when you try to open a
nonexi stent fil e in a mode other than sequential Input, the Open statement creates the fil e
first , th en opens it.

A Simple Text Editor


The Text Edito r application shown in Figure 2 1. l enables a u se r to en ter tex t in a mu lti l ine
text box, the n save th e tex t as a file on disk. It creates, or opens, the file using the Open
statemen t' s seque nti al-access Output mode when saving the text. To enabl e the user to edit
an ex istin g fi le, Text Editor uses the sequential Input mode to open the text fil e. Tex t Ed itor
reads the file , one line ata time, using the Line Input# statement, adding each retri eved line
to th e program vari able Li ne F r om Fi l e$ . When the end of the file is reached, the vari able
Li neFromFi le$ is ass igned to the Text property of the multiline text box .
The file ' s co ntents can be changed simply by changing the text in the text box , the n
overw ritin g the original file with the new text. The maximum length of a fil e that can be
edited with Text Editor is a little less than 64,000 bytes, because that is the max imum
number of characters you can assign to a Vis ual Basic multiline text bo x control.

Microsoft Visual Basic Programmer 's Guide


Chapter 21 Processing Files 321

1m Text Editor aa

+
+I + 1!!11

Open Save Exit

Figure 21.1 The Text Editor Application

Setting Properties of the Text Editor


To start building the Text Editor application, create a form and add the controls li sted in the
following table. Text Editor requires a multiline text box control to accept the text from the
file, plus buttons to open a file, save a file (or clear the text box), and exit from the
application.
Setting for Setting for
Control CtlName property Caption property other properties
Tex t box FileTextBox MultiLine = True
ScrollBars = Both
Command button OpenButton Open File Default = True
Command button SaveButton Save/New File
Command button ExitButton Exit

Remember to give each control the CtlName and Caption properties shown in the preceding
table. Otherwise code that relies on these properties won ' t work properly.

How the Code Works


Five event procedures (plus severa} general procedures), are required for the application .
The event procedures for the form initialize the application and resize the text box when the
form is resized. The event procedures for the controls enable the user to save text as a new
disk file , load a pre-existing file for editing, or terminate the application. The general
procedures are called whenever their action is needed.

Microsoft Visual Basic Programmer's Guide


322 Part 4 Adv anced Applications

The procedures used in the Text Editor are shown in the following table.
Procedure Description
ExitButton_Click Enables the user to close the application . If there is text in
the text bo x, asks the user whether it should be saved, and
<loes as instructed. Closes all files , then terminates the
program by unloading the form .
Checkltüut Determines if there is text in the text box that may need to
be saved, then asks the user whether or not to save it.
GetName Gives the user an opportunity to name or rename a file to be
opened or saved.
OverWrite When the user wants to save a file , thj s procedure is called
no matter whi ch button click initi ated th e save ac tion .
Form_Load Starts the application. Tells the user what can be done and
how to proceed.
SaveButton_Click Enables the user to save the text as a file on disk. If a file is
loaded, this button can be used to clear the old text in
preparation for creating a completely new file.
OpenButton_Click Enables the user to edit an existing file. If there is already
text in the text box, asks the user whether it should be saved.
Does as instructed, then closes the file . Next, shows a dialog
box to get the name of the new file to display. If the file
exists, ope ns it and reads its contents into the multiline text
box . If the fil e cannot be found, the user can choose whether
or nol to crea te it, or try a new name.
Fileüpener Given a fil ename and mode in which it is to be opened ,
Fil eüpener ope ns the file and retums the number by which
the fil e is thereafter to be known.
FileErrors If a run-time error occurs during an attempt to open a file or
read from the di sk, this procedure examines the errors and
retums a code indicating what action to take.
Co nfirm Fi le Checks to make sure a file exists. If the user is saving text
and the file ex ists, he is remjnded that the save will
overwrite the current contents. If the user is trying to open a
nonexistent fil e, he is given the option of creating the fil e or
trying another filename.

Note The Fi leErrors and ConfirmFile Function procedures were created in Chapter 19,
" Handling Run -Time Errors," and are called from procedures in the Text Editor application
when appropri ate. The Fileüpener Function procedure was created in the previous section
in thi s chapter. Be sure to enter or load th ose procedures into the Tex t Editor module.

Micro soft Visual Basic Programmer's Guide


Chapter 21 Processing Files 323

The example code presumes you have retained the default form name for the application .
Merge the contents of the file CONSTANT.TXT with the global module, then enter the
following lines:
' Constants to represent the file-access modes.
Global Const SAVEFILE = l. LOADFILE = 2
Global Const REPLACEFILE = l. READFILE = 2, ADDTOFILE 3
Global Const RANOOMFILE = 4, BINARYFILE = 5

' Constants to repre s ent error conditions .


Global Const Err_OeviceUnavailable = 68
Global Const Err_Oi s kNotReady = 71, Err_ FileAlreadyExists = 58
Global Const Err_TooManyFiles = 67, Err _RenameAcrossDisks = 74
Global Const Err _Path _FileA ccessError = 75. Err_DeviceIO = 57
Global Const Err _DiskF ul l = 61, Err_BadFileName = 64
Global Const ErrBadFileNameOrNumber = 52. Err_ FileNotFound = 53
Global Const Err_PathDoesNotExist = 76. Err_BadFileMode = 54
Global Const Err_FileAlreadyOpen = 55. Err_ InputPastEndüfFile - 62

Global Const MB_EXCLAIM = 48, MB_STOP = 16


Global WorkingFileName As String ' Path and filename in form .

The ExitButton Click Procedure


Enter this procedure for th e command button named ExitButton:
Sub ExitButton_Cli ck ()
• Call procedure t o ens ure t ext in the box won't be lost.
Checkltüut Fil eTextBox
Clase ' Cl ase al l f il es opened by this application.
End ' Term í na te t he application with End statement .
End Sub

The CheckltOut and GetName Procedures


ExitButton_Click first cal Is the general procedure CheckltOut, and if there is already text in
the text box, this procedure gives the user an opportunity to save the current contents . But
because CheckltOut is called by other procedures besides ExitButton_Click, it does more. If
the user decides against saving, the SaveButton caption is set to "Save/New File" and ali
files are closed. No matter which choice was made, the text box is then cleared, and the title
bar of the form is set to reflect that no file is currently loaded . If the user wants to save the
text, a general procedure call ed GetName prompts the user for the name of the file in which
to save the text. Then the OverWrite procedure is called to replace the file ' s current contents
(if any) with the text in the text box .

Microsoft Visual Basic Programmer's Guide


l24 Part 4 Advanc ed Applications

Sub Che ck ltüut (TheTextBox As Control)


If The TextBo x .Text <> "" Then · If box co ntains text,
Ms g$ = "D o you want to s ave this text?" · find out if it s hould
An swer% = MsgBox(Msg$; 52, "Hey!") · be saved.
If Ans wer % = 6 Then · If user answers OK,
Get Name ( "Sa ve As:") ' get a filename.
Call Over Writ e(T heTe xt Box) ' and overwrite the file .
El self An swer% = 7 Then • If not, adjust caption .. .
Save Button . Caption = "Save/New File"
Close ' ... then el ose all files.
End I f
Th eTex tBo x . Te xt · Empty the text box.
Form l . Capt ion "Text Editor" · Reset th e title bar.
End 1

End Sub

Sub Ge t Name ( LoadOrSave As St ring )


Ge t the fil ename from the user.
Name ToUse $ = InputBox $(Loa dOrSave, "Fil e name", WorkingFileName)
' Conv e rt the name to uppercase letter s far consistent appearance.
Worki ngFil eName = LTrim$(RTrim $(UCa s e$(NameT oUse$)))
End Sub

The OverWrite Procedure


The Ü\-er\\.rite proced ure performs the task of actuall y pl ac ing the curren ti y di sp la yecl text
in to a fil e. The te xt to be saved is passed in as a property of the argument Th eBox. The first
line call ,, thc Fu nctio n procedure ConfirmFile to see whether the file already exists. lf it
does , th e u:,e r is as ked to confirm the intention to overwrit e the file. If the user wa nts to save.
Fil eüpener is called to open th e file in Output mode. If it succeeds, Fileüpener return s th e
file num ber which is thereafter used to refer to the fil e. The Print # statement overwrites the
old content '> of the fil e with th e tex t from the text box, th en the file is closed. With sequenti al
file acce ss it is co mm on to close a file immediately after reading from or writing to it,
because a file openecl in one seq uential mode must be closed before opening it in a differen t
seq uenti al mocle: otherwi se, the error "File already open" is ge nerated .
Sub OverW r i te (T heBox As Cont rol)
I f Confi rmFile(( Work ingFileName) , ReplaceFile ) Then
If the fil e exist s , call Fileüpener to open it. then place the text
as is i n the file and cla se the f il e.
Fil eNu m% = FileOpener(( Work ingF i leNam e) , ReplaceFile, 0)
I f File Nu m% = 0 Then Exit Sub
On Er r or GoTo Writ eError
Prin t #FileNum%, TheBox.Text
Clo se Fil eNum%
End I f
Exit Sub

Microso ft Visual Basic Programmer's Cuide


Chapter 21 Processing Files 325

WriteError:
Action% = FileErrors(Err) ' If there was an error accessing the file,
Select Case Action% ' find out what to do, then do it.
Case 0
Resume ' Try the statement that failed again.
Case 1
Resume Next ' Forget the statement that failed; just
Case 2 ' go ahead and do the rest of procedure.
Exit Sub ' Exit the Sub procedure right away .
Case Else
Error Err ' If the error is completely unanti cipated.
End ' display system error message, then quit .
End Select
End Sub

lf an error occurs in OverWrite, Fileüpener, or ConfirrnFile, their error handlers cal! the
FileErrors Function procedure to analyze the error.

The Form_Load Procedure


Enter thi s code for the Form_Load procedure:
Sub Form_ Load ()
CurrentX = 100 : CurrentY = 100 ' Position the form on desktop.
Forml.Caption = "T ext Editor"
BoxCaption$ = "Using " + Forml.Caption
NL$ = Chr$(13) + Chr$(10) ' Combination needed far line break s .
' Display a message telling the user how to start using the editor.
Msg$ "If you want to create a new text file,"
Msg$ Msg$ + NL$ + "choose OK, type in your text, and then "
Msg$ Msg$ + NL$ + "choose Save/New File."
Msg$ = Msg$ + NL$ + NL$ + "To open a fil e that al ready exi sts on disk. "
Msg$ Msg$ + NL$ + "choose OK, choose the Open Fil e button, "
Msg$ Msg$ +" and type the name of the file you want to open."
MsgBox Msg$, 64, BoxCaption$
End Sub

Other than Form_Load, the only events your application code must respond to are the Click
events for the command buttons. The Click procedures are listed in the following sec tion s.

Microsoft Visual Basic Programmer's Guide


326 Part 4 Advanced Applications

The SaveButton_Click Procedure


/
The SaveButton_Click procedure e;:hables the user to either load a new file or save the
current file , then clears the text bo'x to start a new file. Whether text is to be cleared or a file
is to be saved is determined by whether the caption on the button is "Save/New File" or
something else ("New/Save File" is the altemative). In either case, the user is always given
the option to save the text to disk befare it is cleared.
Sub SaveButton_Click ()
' First check whether the button is currently being used far s aving
'text, or far clearing it . If its caption is "Save/New File", then
' s ave FileTextBox.Text. Otherwise ask if the text should be sa ved,
' do as instructed, then clear FileTextBox.Text by ass ignin g "" .
If SaveButton.Caption = "Save/New File" Then
GetNa me ( "Sa ve As :" ) ' Qu e ry user fo j filen am e.
Call OverWrite(FileTextBox) ' Overwrite th e file
SaveButton . Caption = "New/Save File" · with new text .
El se
· If the button is being used to clear the text box far new
· text, call Checkltüut to see if old text should be saved.
Checkltüut FileTextBox
SaveButton.Caption = "Save/New File" ' Reset button capt io n.
End I f
End Sub

The OpenButton_Click Procedure


The OpenButton_Click procedure permits loading a text file that already ex ists on di sk. It
ca!J s CheckitOut, GetName, ConfirmFile, and Fileüpener. Fileüpener stilJ uses the
sequential -access form of the Open statement, but in Input mode (reads the fil e in ), rather
than the Output mode (overwrites the file).
lf Fileüpener opens the file successfully , a loop is used toread its contents until the EOF
function returns True, indicating that the end of file has been reached. With each iteration of
the loop, the Line Input# statement places a single line from the file in the variable
Ne x t Li ne$ . Line Input# recognizes the end of a Iine when it finds the carri age return-
1inefeed sequen ce Ch r $ ( 10) + Ch r $ ( 13) . However, it does not place the carriage return-
1i nefeed into the variable with the line. Therefore, the code terminates each line placed in
NextL i ne$ with a carriage retum-linefeed sequence. Nextl i ne$ is then appended to the
Li neFromFi le$ variable that contains ali the lines read so far.

Mic rosoft Visual Basic Programmer's Guide


Chapter 21 Processing Files 327

Sub OpenButton_Click ()
CheckltOut FileTextBox ' See if there is text to save.
GetName ("File To Open:")
If WorkingFileName <> "" Then
OpenMode% = LOADFILE
If ConfirmFi le(WorkingFileName, OpenMode%) = 1 Then ' If file exists.
FileNum% = FileOpener(WorkingFileName . OpenMode%. 0) • try to open.
If FileNum% - 0 Then Exit Sub · If open fails,
If OpenMode% = ReplaceFile Then · just exit; if
Clase FileNum% ' OpenMode was set
Exit Sub ' to Rep l aceFile, it is
End I f ' empty, so you can
Else ' clase it and exit .
Exit Sub ' If the file s till doe sn ' t exist...
End I f
Else ' _or if the user failed to enter
Exit Sub ' any filename at all.
End I f ' then just stop trying.

' Several stateme nts in this procedure use file numbers as arguments,
· so turn on an error tra p and leave it on far remainder of procedure.
On Error GoTo ReadError
' If the file ' s text won't fit comfortably into the text box. exit.
If LOF(FileNum%) > 60000 tnen
Msg$ = "Sorry your file is too larg e to edit."
MsgBox Msg$, 16. "File Too Big"
Exit Sub
End I f
' Otherwise. read one line ata time into a variable .
' Do Un ti 1 EO F( Fi 1e Num%)
Line Input #FileNum%, Nextline$
' As eac h line is read, add it to those preceding it. then
· replace the terminator (Line Input# drops the line-break
· characters so you have to add ,them back).
LineFromFile$ LineFromFile$ + Nextline$ + Chr$(13) + Chr$(10)
Loop

' Put the file contents into the text box.


FileTextBox.Text = LinéFromFile$
' Change title bar to indicate file being edited.
Forml.Caption = "Text Editor Now Editing : " + WorkingFileName
' Change caption on Sa ve/New File button so it can be used
' to clear current text from the text box.
SaveButton.Caption = "New/Save File"
· Once text is read in, clase the file.
Clase FileNum%
Exit Sub

Microsoft Visual Basic Programmer's Guide


Part 4 Advanced Applications

ReadError:
Action% = FileErrors(Err)
Select Case Action%
Case 0
Resu me
Case 1
Re s ume Next
Case 2
Exit Sub
End Select
End Sub

When text is loaded from a di sk fil e into the tex t box , the caption on SaveButton changes to
"New/Save Fil e'· to remind the user th at tex t can be di scarcled w ith out be in g saved.
Otherwise. the caption is "Save/New File. "

Using the Filelnfo Dialog Box


You can modify the OpenButton_Click proceclure to use the Filelnfo clialog box (created in
C hapter 20, " Using the File-System Controls") instead of GetN ame. Be sure to define the
string variables TheFi l eName and TheNewPath in the global modul e. Replace the call to
GetName with the a call to following procedure wherever you want to enable th e user to
search the file sys tem for a fil e to open :
Sub FileB ox (Header As String)
FilelnfoTitle = "Op en Fi l e" Name for Filelnfo title bar.
Filelnfo.Show MODAL ' MODAL i s Defined in CO NSTA NT.TXT.
· Assign the parts to the wh ole .
Working Fi leName = TheNe wPat h + TheFileName · Str ing f or Open.
End Sub

The argument MODAL di sables the res t of the application until the user closes the Filelnfo
dialog box by choosing either DlgB utton (0) (the OK button) or DlgB utto n( 1) (the Cancel
button) . MODA L is defined in the CONSTANT.TXT file , which should be merged w ith
yo ur global module.
T he Text Ed itor application is written to preserve line break s as they exist in the
filedvbpgapaafter eac h Line Input# statement , a carri age return-linefeed is appended to the
line. l f you do not add the line breaks, how the tex t wraps in the text box depends on
whe the r or not the tex t box has a hori zon tal scroll bar.
lf no ho ri zontal sc roll bar is prese nt, the lines are wrapped to fit in th e current wi dth of the
tex t bo x. If the box has a horizontal scro ll bar, text is added to the box until the max imurn
line leng th (255 characters) is reac hed , the n another line begins.

Microso ft Visual Basic Programmer's Guide


Chapter 21 Processing Fi les 329

The Form Resize Procedure


You can add code to the Form_Resize procedure so the user can enlarge the form
horizontally to accommodate longer lines. The conditions (such as ScaleHeight - 600 > 1)
prevent an error if the form is made too small to contain the controls and prevent the buttons
from becoming overlapped if the form is contracted horizontally.
Sub Form_Resize ()
If Window State <> 1 Then ' 1 = Minimized to icon.
If ScaleHeight - 600 > 1 Then ' Keep text box centere d.
FileTextBox.Height - ScaleHeight - 600
End If
' Keep buttons from overlapping and keep text box centered in form.
If Sca leWid th < 6000 Then ' If the form is less than mínimum
FileTextBo x .Width = 5700 ' width, keep t ext box at mínimum.
Elself ScaleWidth - 200 > 1 Then
FileTextBox.Width - ScaleWidth - 500
End I f
End I f
' Maintain relative button positions.
BoxPlusVBar = FileTextBox.Width + 250 ' Width of text area + scro l l bar .
OpenButton.Top - FileTe xtBox.Height + 200
SaveButton.Top = FileTe xtBox.Height + 200
Sa veButton.Left - Bo xP lu sVBar \ 2 - (.87 * (ExitButton.Width \ 2))
ExitButton.Top = FileTextBox.Height + 200
ExitButton.Left = (BoxPlusVBar) - ExitButton.Width
End Sub

Using the Text Editor Procedures in Other Applications


With minor modifications, the general procedures used in the Text Editor can be used in any
application for which sequenti al file access is needed . Sorne procedures can also be used for
other types of file access.

To use the general proced ures in Text Editor in other applications:


1 From the File menu, choose New Module.
2 Copy each procedure from the Text Editor into the Declarations section of the new
module.
3 From the File menu, choose Save File As and save the module under the name you want.
4 Load the module into each project where yo u need sequenti al file access.

Note that when you call procedures from a separate module or invoke other forms, any
global variables used in the procedures must be declared in the global module of the
application, rather than at the form level of either the application 's start-up form, or the form
level of the new modul e.

Microsoft Visual Basic Programmer's Guide


330 Part 4 Advanced Applications

Later in thi s chapter the GetName, Fileüpener, ConfirmFile, and FileErrors procedures are
used in building an application that uses a random-access file systerp.

Note In gtaphical user interface applications the TAB key is used for moving among
controls. Therefore, pressing TAB within a multiline text box moves the focus to the next
control, rather than inse rtin g multiple spaces. A user who wants to use tabs for spacing
within a multiline text box can press CTRL+I rather than TAB.

Nonconforming Text Files


Not all text fil es use th e same convention to indicate the end of a line. Files written by
languages other than th ose in the Microsoft Basic family may use only a carriage-retum or
line-feed, rather th an a co mbin ation of both , to indicate a line break. However, the Line
Input# statement expects lines to be terminated with the two-character, carriage return -
linefeed combination , represented as CH R$ ( 13 ) + CH R$ ( 10 ) . A call to the general
procedure CheckNewLines can be inserted into the Text Editor's OpenButton_Click
procedure, just before the line:
Do Until EOF(FileNum%)

Pass it the empty string L i neFro mFi le$ and the file 's file number (FileNum o/o).
CheckNewLines uses the Input$ statement to check each character in the file individually.
If CheckNewLines finds the line- break sequence recognized by Line Input#, only th at first
line is assigned to L i ne F r om Fi l e. Then, Line Input# is u sed to read the rest of the fil e' s
contents. If the file has a differe nt line-break character, CheckNewLines reads every
character in the file indi vidual ly, replacing the !in e-break characters with the Ch r $ ( 13) +
Ch r $ ( 10) sequence.
If the user saves the file later, it is written to di sk using the carriage return-linefeed
combination as a line- break seq uence. If the file contains no newline characters of any kind ,
L in e F romF i le$ contains the whole contents of the fil e, but without newline characters.
Sub Che ck Newli nes ( LineFromFile As String, FileNum As Integer)
· Sta rt read ing file one byte ata t ime , l ook ing for carriage return.
Do Until EOF(Fil e Num )
char$ = In put$(1 , Fil eNum)
If char$ <> Chr$ ( 13) Then ' If it isn't a carriage r et urn,
If char$ <> Chr$(10) Then ' c heck wh et her it' s a line f eed.
LineFromFil e$ = LineFromFile$ + c ha r$ ' If not, add it t o
El se ' i ts predecessors .
GotFeed % - Tr ue ' Otherwise, set a flag
Endlin e$ = Inpu t $(1, 1) ' and che ck the next
If Endl ine$ <> Chr$(13) Then ' character .
Endline$ = Chr$(13) + Chr$(10 ) + Endline$
Lin eFromFil e$ = LineFromFile$ + Endline$
End I f
End I f
Else

Microsoft Visual Basic Programmer 's Guide


Chapter 21 Processing Files 331

GotReturn% = True ' If it was a carriage return . see if


Endline$ = InpuU(l. 1) ' the next character is a line feed.
If Endline$ - Chr$(10) Then 'If it is, the line s have the
GotCR_ LF% = True ' correct line - break sequence.
Endline$ = Chr$(13) + Chr$(10)
Else
Endline$ = Chr$(13) + Chr$(10) + Endline$
End If

LineFromFile$ = LineFromFile$ + Endline$

If GotCR_ LF% = True Then ' If it ha s a correct line-break


Exit Do ' sequence exit the lo op and return.
End I f
End If
Loop
End Sub

Records in Random-Access Files


Tbe Text Editor example assumed that the data from the sequential file would be placed in a
multiline text box and treated as one long string of text. However, you often need to deal
with files that contain data representing many individual records, eac h having the same
number of the same types of fields. In other words, the forrn of each record is the same, but
each contains different actual data in the individual fields. This section discusses how you
can organize data as discrete records, and then write data to , or read data from , a random -
access file.
Random-access records are stored quite differently from sequenti al records. Each random-
access record is defined with a fixed length, as is each field within the record. These fixed
lengths determine where a record or field begins and ends, as there are no delimiters
separating fields, and no carriage retum-linefeed sequences separatin g records. Figure 21.2
shows how three records rnight appear in a random-access file .

JRecord 1 1Record 2 Record 3

IMlclGlulilrlel 11IMlalnlalglelrlsl l~lolslsl 11111IElctliltlolrl 131hlhlolsltlalklolvlilwlrlil 1

, lFie/d 1 , ~ 2t::,d 3 lField 1 , '----r Fielel~ IFi~ld 3 lFie/d 1,


Figure 21 .2 How records appear in a random -a ccess file

Microsoft Visual Basic Programmer's Guide


332 Part 4 Advanced Appl icati ons

Creating and Adding Data to a Random-Access File


Assume you arrive at work one morning anda memo from your manager informs you that
the company wants to compare the age and gender of each employee to their salaries to
determine whether the company is di scriminating against older or female workers. Because
such bias is against the law, the company's employee files do not currently have the gender
and _age information integrated with other e mployee information. Your manager has hired a
temporary worker to input the information , but needs a quick record-entry program so the
work can begin. You created a quick text editor program last week, and now you need to
create a record-entry program .

To create an application that adds records to a random-access file:


1 Create a forrn for data input.
2 Define a variable to represent the collec tion of fields constituting each record.
3 Open the file in Random mode and specify the length of each record.
4 Get input for a new record and store the record in the file .

Although creating the form naturall y precedes the other steps, we'll look at Steps 2, 3, and 4
first for an overview of using random file access. Then we'll put the Record Editor
application together.

Defining Records
To accept records from a random-access file, yo u need a variable in your program th at can
treat the collection of individual data fields as a single variable. The Type ... End Type
statement enah les you to create a com pO~i lC clalél type th at mixes strin g and numeric
elements. You then use this data type to define a variable to accept records from th e file.
You can defin e these user-defined types only in the global module.
For more information about user-defi ned types. see Chapter 17, "Advanced Language
Features ... or:

m Search Help for:


user-defined

Microsoft Visual Basic Programmer's Guide


Chapter 21 Processing Files 333

The fo llowing examples use this user-defi ned type:


' Defin e t he RecordType structure:
Type RecordType
RecordNum As Long ' Sto re s the number repre se nting position
LastName As String * 20 ' of re cord within the file.
FirstName As Stri ng * 15
Ag e As Integer
Salary As Currency
Gender As String * 1
End Type

The first field contains a value corresponding to the record's position in the file.
Note that whi le Vi sual Basic permits variable- length strin gs within user-defined types, you
must use fixed- length strings in records that will be placed in a random-access file , because
the correspo ndin g data in each record field must be the same length.
When definin g the field s for random-access records, you must allow for the larges t possibl e
value th at eac h field will contai n. Far example, whi le a person's age will not exceed the
range for an integer, it is quite possible that in a large corporation, the number of employees
may exceed the largest acceptable Integer value. In the example, this would mean that you
should use the Long data type far the Re cor dNum variable. You should make RecordNum
Long.
When fi elds contain strin g data, sorne space is necessarily wasted, because data such as
people 's names vary in length . When a value is assigned to the field, if the ac tual string data
entered in a fie ld is less th an the length with which the field was defined, the trailing space is
automati call y padd ed with blanks (Chr$(32)). Conversely, if you are storing record s
co ntainin g numbers, using random -access file s can conserve disk space when co mpared with
using sequential fil es. Thi s is because sequential files save numbers as a seq uence of
characters representing each digit, whereas random-access file s save numbers in binary
format.
For example, th e number 17000 is represented in a sequential fil e using five bytes , one far
each di git. However, if 17000 is stored in an integer field of a random-access record , it takes
on ly two bytes of disk space.
Integers in random-access files take two bytes , lon g integers and single-precisio n numbers
take four bytes, and double-precision numbers and currency data types take eight bytes.
Recall that after declaring the form of the user-defi ned type, you must define a variab le of
the type the same way you define any other variable:
' Declare t he variable RecordVar having the type RecordType:
Dim RecordVar As RecordType

The program fragments in the next section assume th at this variable has been dec lared in the
global module .

Microsoft Visual Basic Programmer's Guide


334 Part 4 Advanc ed Applications

Opening the File and Specifying Record Length


As you noted earlier in the chapter, the syntax for the Open statement enables you to specify
a record length when opening for random access. If you don ' t specify a record length, record
length is assumed to be 128 bytes. The syntax for opening a random-access file is:
Openfile$ For Random As [#]filenumbero/o Len= RecordLen o/o

If you recall the Fileüpener example in the section "Opening a File," the case that opened a
random-access file used a Len = clause in the Open statement. A value for Len = was
passed into Fileüpener as the argument RecordLen. The "buffer" for a random-access file
must be exactly the size of one record in the fil e. This must in turn correspond to the size of
the variable of the user-defined type used to receive the data from the file. The length of a
user-defi ned type can be obtained by passing a variable of the type to the Len function . For
ex amp le. to open a file whose records correspond to the Reco rdType type, a value for th at
argument in Fileüpener could easily be calculated in the call as follows , by passing the
variable name RecordVa r to Len:
Con st RANDOMFILE - 4
AName$ = "RecFi l e. XYZ"
' Open a file to hold records of RecordType.
Fi l eNum% = FileOpener(AName$, RANDOMFILE. Len(Rec ordVar))

Using the Get and Put Statements with Random-Access Files


W ith a variab le of the proper type defined to hold the data fields of a record from the fil e,
you can use the Get statemen t to retrieve a record from th e file, and the Put statement to
place new or edited records into the file. The syntax for these statements is :
Get [# ]filenumbero/o, [recordnumbero/o], recordvariable
Put [# ]fil enumbero/o , [recordnumbero/o ], recordvariable

T he # is opti onal, as is recordnumber. If no recordnumber is specified, the fields of the nex t


record are placed in the corresponding fields of recordvariable (in the case of Get) ; with
Put, the fie lds of recordvariable are placed into the fil e at the next record position .

Example The Function procedure CopyFile receives the names of the files to copy from and copy to,
plus the type of fil e access. A variable of the type used to receive the file 's records is defined
as Re e Va r. The user-defined type RecordType must be defined in the program 's global
module.
CopyFile first determines the length of a single record, then checks that the names are val id
and that a record has a length. After that, each file is ope ned. The number of records in the
source file is determined by dividing the length of th e fil e by the length of a single record . In
a loop that starts with the first record and progresses to the last, the Get statement retri eves a
record from the ex istin g fil e and the Put statement places that record into the new file . When
th e loop conc ludes, both files are closed, and the Function procedure returns True if no
signi ficant eITor was encou ntered . The FileErrors Function procedure, called from the error
handl er, is the sa me one th at was created in th e preceding chapter and used in the Text
Editor example.

Mic roso ft Visual Basic Programmer's Cuide


Chapter 21 Processing Files 335

Function CopyFile (OldName$, NewName$ , FileType%) As Integer


Oim RecVar As RecordType
Recordlen% = Len(Rec Va r)
If Ol dName$ = "" Or NewName$ = "" Or Recordlen% - 0 Then Exit Function
On Error GoTo CopyError
OldNum% = FileOpener(OldName$, FileType%, Recordlen%)
NewNum% - FileOpener(NewName$, FileType%, Recordlen %)
If OldNum% <> 0 And NewNum% <> 0 Then
For Ind% = 1 To LOF(OldNum%) \ Recordlen%
Get #OldNum%, Ind%, RecVar
Put #NewNum%, Ind%, RecVar
Next Ind%
End I f
Close OldNum%
Close NewNum%
CopyFile = True
Exit Fun ct ion
CopyError:
Action% = FileErrors(Err)
Select Case Action %
Case 0
Resume
Case 1, 2
CopyFile = False
Exit Function
Case Else
Error Err
End Select
End Function

Note that the second argu ment to the Get and Put statements co uld be omitted in this
example, because the loop proceeds one record at a time:
Get #O ldNum%, RecVar
Put #NewNum%, . RecVar

It is a good idea to call ConfirmFile befare calling a procedure such as CopyFile to


determine whether NewName$ is the name of a pre-existing file. For example, you could call
ConfirmFile first and only call CopyFile if ConfirmFile retumed zero (with a random or
binary file , a zero retum indicates the file does not yet exist). If it already exists, you could
give the user an opportunity to ei th er give another name for NewName$, or overwrite (or
delete) the old file befare copying.

Microsoft Visual Basic Programmer's Guide


336 Part 4 Advanced Applications

The Record Editor Application


Design the Record Editor form with the controls and properties listed in the following table,
and arrange the controls as shown in Figure 21.3. Record Editor requires a single-line text
box control for five of the six RecordType fields. These text boxes allow the program to
display data to, and accept data from, the user. (See Chapter 10, "Responding to
Commands," for information on associating labels and access keys with text boxes.) The
command buttons are used to open a file, store the currently displayed record in the file ,
create a new record, delete an old record, display different records on the form, and exir
from th e application .
Controls CtlName property Caption property
Textbox FieldBoxes
Text box FieldBoxes
Textbox FieldBoxes
Textbox FieldBoxes
Textbox FieldBoxes
Command button NextRecord &Next Record
Comrnand button PreviousRecord &Previous Record
Command button OpenFile &Open File
Command button AddRecord &Add Record
Command button DeleteRecord &Delete Record
Commanc.l butl o n Ex itButton E&xit

No te that each text box has the same name, FieldBoxes. When you type in the CtlNarne
property of the second text box, Visual Basic asks if you want FieldBoxes to be a control
array . An swer Yes. Thereafter you can refer to each box with the name FieldBoxes followed
by its index number in parentheses. For example, the text box labeled First Name will be
FieldBoxes(0). Last Name will be FieldBoxes(l) and so on (assuming you name them in that
order).

1m Record Editor: "Tmp4612.466 aa


11
Fir st Name Last Name
S-alary !~--~¡ Ag~ D S~x O
1 Next Record 1 1E'revious Record I gpen Filej

1 ~dd Record ! I Delete Record 11 E2!;it 1

Figure 21 .3 The Record Editor Application

Microsoh Visual Basic Programmer's Guide


Chapter 21 Processing Files 337

How the Code Works


Seven event procedures (plus severa! general procedures), are required far the Record
Editor. These procedures initialize the application , then provide the appropri ate action wh en
the user clicks one of the buttons. The general procedures are called whenever their action is
needed. The FileErrors and ConfirmFile Function procedures are those created in Chapter
19, "Handling Run-Time Errors," and used in the Text Editor example. Fileüpener and
GetName were created earlier in thi s chapter. As with Text Editor, you can use the Filelnfa
di alog box (created in Chapter 20, "Using the File-System Controls") and substitute the
FileBox procedure far GetName when the user wants to open a file.
Procedure Description
Form_Load Starts the application and starts a temporary fil e.
Show Record Pl aces the new reco rd 's data in the text boxes when a
differe nt record is displayed.
OpenFile_Click Enables the user to open an existing data fil e.
CheckEmüut Examines fi elds to see whether or not they have been edited.
Called whenever a new record is di splayed.
Nex tRecord_ Click Displays the next consecutive record .
PreviousRecord_ Click Displays the previous record.
AddRecord_ Click Presents a blank copy of the farm .
ClearFields Empties the tex t boxes when a new record is to be ad ded .
DeleteRecord_Click Removes the currently di splayed record and di splays the
next consec uti ve record.
Ex itButton_Cli ck Cleans up any deletions and writes ali data to fi le.
WriteQuery Queries the user whether or not to save the fi le.
CleanUpFile When a fil e is saved, CleanUpFile perm anentl y removes any
records deleted during the editing session.
CopyFile, Fil eü pener, Created earlier in thi s chapter.
GetName
Co nfirmFil e and F il eErrors Created in Chapter 19, "Handling Run -time EITors."

Microsoft Visual Basic Programm er's Guide


338 Part 4 Advanced App lications

The global module far the Record Editor application is similar to that far Text Editor. In
fact, all the Global Const definitions are the same. In addition to the definitions copied from
the file CONSTANT.TXT, the global module should contain the fallowing:
Global Const NUMBOXES - 5
Global Const SAVEFILE = 1, LOADFILE = 2
Global Const REPLACEFILE = 1, READFILE = 2, ADDTOFILE 3
Global Const RANDOMFILE = 4, BINARYFILE - 5

' Define a data type to hold a record:


Type RecordType
RecordNum As Long ' Keep track of record order in file .
FirstName As String * 15
LastName As String * 20
Salary As Currency
Age As Integer
Gender As String * 1
End Type
' Define a variabie of the data type.
Global RecordVar As RecordType
Global RecordNumber As Long · The actual record number (in file) .
Global Position As Long ' Position describes presentation order .
' Define global variable s to ho l d the file number and record number
' of the current data file.
Global WorkingFileName As String ' Default filename to show in dialog boxes.
Global WorkingFileNum As Integer
Global BakName As String ' Name for a backup file, if one is created .
Global LastRecord As Long
Global TempFileFlag As Integer
Global NewRecordFlag As Integer
' Define a string array to hold previous contents of the current record. Use
' string array because you'll be comparing text box strings rather than
' record-file values.
Global OldContents(0 TO 4) As Stri ng
' Define these if you want to use the Filelnfo dialog box
' when Open button is chosen .
Global FileinfoTitle As Stri ng
Global TheNewPath As String
Global TheFi l eName As String

Microsoft Visual Basic Programmer's Guide


Chapter 21 Processing Files 339

The Form Load Procedure


The Form_Load procedure for Record Editor is similar to that for Text Editor. It instructs
the user to either open a file or start adding records. However, regardless of which choice is
made, a file is opened. If the user doesn't specify one, a temporary file is created to hold
records until the Exit button is pushed, at which point a filename is requested.
Sub Form_ Load ()
CurrentX = 100 : CurrentY = 100 ' Initialize position and title bar .
Forml. Caption = "Re cord Editor"
Bo xCaptio n$ = "Using " + Forml.Caption
NL$ = Chr$(13) + Chr$(10) ' Define a newline character seq uence .

' Display a message telli ng the user how to start using the editor.
Msg $ - "If you want to create a new record file, choose OK,"
Msg$ = Ms g$ +" then choose Add Record to add a new record."+ NL$
Msg$ - Msg$ + NL$ + "To load a file that already exists"
Msg$ - Msg$ +" on disk," + NL$
Msg$ - Msg$ + "choo se the Open File button and type the name"
Msg$ - Msg$ +" of the file you want to open."
MsgBox Msg$, 64, BoxCa ption$

' Create an unlikely temporary filena me.


WorkingFileName = "-Tmp" + Right$(Time$, 2) + Left$(T ime$, 2) + "."
Workin gFile Nam e = WorkingFileName + Right$(Time$, 2) + Right$(Time$, 1)
· Check to make sure you don't ruinan existing file.
If ConfirmFile( Working Fi l eName, RANDOMFILE) The n
Msg$ = "T emp. file,"+ Work ingFile Name + " , found. Choose OK to erase"
Msg$ = Msg $ + "current contents. or choose Cance l to load itas it is."
If Msg8ox(Msg$, 33 , "Old temporary file found !" ) = 1 Then
Kill WorkingFileName
End I f
End If
' Open the temporary file and check if it has records.
Workin gFileNum - FileOpener(WorkingFileName$, RANDOMFILE, Len(Record Var))
LastRecord = LOF(WorkingFileNum%) \ Len(RecordVar)
If La stReco rd - 0 Then ' If it's em pty prepare to add record s.
NewRecordFlag = True
El se ' Otherwise display the first record .
RecordNumber - 1
Position = 1
ShowR ecord
End I f
TempFileFlag% = True ' Set flag indicating a temporary file.
FieldB oxes( 0).SetFocus ' Put cursor in first text bo x.
End Sub

Microsoft Visual Basic Programmer's Guide


340 Part 4 Advanced Applications

The name for the temporary file is designed to increase the likelihood of its being unique. lf
no such file is found , the temporary file is created with the Fileüpener call and
NewRecordFl ag is set to True, because the only thing you can do with an empty file is to
add records to it. Using the SetFocus method places the cursor in the first text box (you
could !abe! it First Name), so the user can begin entering data right away. Later, when
closing the application, the user can give the file a permanent name, or simply abandon it. In
either case. the temporary file is deleted.
If the temporary file already exists (unlikely, but possible), the user can choose either to
delete it or load it and display the first record. The user could then add more records to the
file without overwriting any that were already in the file. The following key statement makes
thi s work:
LastRecord = LOF(WorkingFileNum%) \ Len(RecordVar)

Here is what happens:


1. The LOF function calculates the total number of bytes in the file. lf the file is new or
contains no records, LO F ( 1) retums the value O.
2. The Len ( RecordVa r) statement calculates the number of bytes in one record.
(Record Var is a variable with the user-defined type RecordType.)
3. The number of records is equal to the total bytes in the file divided by the bytes in one
record . This is another advantage of having a fixed-length record. Because each record is
th e same size, you can use a formula to calcu]ate the number of records in the file .

The ShowRecord Procedure


The ShowRecord Sub procedure is called by the Form_Loacl proccdure. lt use s a Get
state ment to retrieve a record from the file, then show the field s on thc form. umeric fi e lds
are clisplayed only if their value is nonzero. This permits easier adclition of inforrnation to
those fields , because the zero need not be cleleted first. The values are also placed in th e
elements of the 01 dContents array, so any changes to the fields ca n be detectecl by
cornpariso n to their previous contents.
ote th at the variable Pos i ti on is assigned to the variable RecordNumber , which is the n
used in the Get statement. At this point, Pos i ti on and RecordNumber are always the sa me
valu e because the order of display is the same as the order of records in the file . However, it
is comrnon practice to add indexing code to programs using random-file access to permit the
records to be displayed in a variety of orders. If you are referrin g to individual record s
indirectly through indexes, Pos i ti on 's are usually different frorn Record Numbe r. Al so
note that, even with indexing, the order of records in the file alway s remain s the same ,
regardle ss of the order in which they are displayed in the program.

Mic rosoft Visual Basic Programmer's Guide


Chapter 21 Processing Files 341

Su b ShowRecord ()
I f Last Record > 0 Then
' Co nv ert di sp l ay - a rd e r posit i on to a file - record positio n.
Record Number = Position
Get WorkingFi l e Num, RecordNum ber, Record Var
Fi el dBoxes(0).Text = Reco rdV a r . Fi r s tN ame
Fie l dBoxes(l).Text = Reco rdVa r . Las tName
' Don ' t put ze r oes i nto text boxes.
If RecordVar . Salary <> 0 Then
Fie l dBoxes(2) . Text = Str$(Recor dV ar . Salary)
El s e
Fie ld Boxes(2). Text
End I f
I f Reco rdVar.Ag e <> 0 Th en
FieldBo xes(3) . Text - Str$(Record Var . Age)
El s e
FieldBoxes(3). Text
End I f
FieldBoxes(4).Text = Record Var.Gender
' Sa ve val ues s hown in text boxes later compariso n.
Ol dConte nts(0) = Fi eldBoxe s (0 ) . Text
Ol dCo nte nts(l) - FieldBoxes(l) . Text
Old Content s (2) = FieldBo xes (2).Text
Old Co ntent s( 3) = FieldBo xes (3) . Text
Old Co ntent s( 4) FieldBox es (4) . Text
El se
Clea rFi eld s ' I f th e r e a r e no rec ord s , ma ke s ur e fie l ds a re cl ear ed .
End I f
En d Sub

Note th at ali th e variables in thi s procedure are global ( th at is, Wor ki ng Fi l e Num ,
RecordNum ber, Pos i t i o n, Re cordVar, LastRecord and the 01 dConte n ts array). The
FieldBoxes contro l array is known throughout the form mod ule as well.

The Openfile_Click Procedure


If the user chooses the Open F ile button to open an existing data file, a check is made to see
if any data was entered in the te mporary fil e. If so, the user is given an opportunity to save
that fi le before di spl acing it with the new fil e. T he code searches for the name specified fo r
the new file . If the fil e doesn ' t ex ist, the user can either create it or aban don the attempt to
ope n, th en try again . If the fil e ex ists or is created, a back up (with the extension .BAK) is
created firs t, then the fil e is o pe ned and the first record is di splayed.

Microsoft Visual Basic Programmer's Guide


342 Part 4 Advanc ed Applications

Sub OpenFile_Click ()
' If the file needs sa ving, get use r' s pe rm ission, then clean up .
If LastRecord > 1 Or CheckEmüut() Then
If WriteOuery(NewFileName$) = True Then
Clean Up File ( NewFileName$)
End I f
End I f
Get Name "Please enter fi l e to open:»
TheName$ = WorkingFi l eName
I f TheName$ = "" Then Exit Sub ' If fil e doesn' t exi st. and user doesn 't
Result% = 1 want to create it, use r will change thi s valu e.
If Confi rmFi le( Th eName$, RAN DOMFILE) - False Then
Msg$ = "Couldn ' t find "+ TheName$ + "."
Msg$ = Msg$ + " Do you want to create " + TheNa me$ + " ?"
Result% = MsgBox(Msg$, 65, "Fil e Not Found" )
End I f
If Result% = 1 Then ' Mak e a backup file . Fi r st.
Period% = InStr(l, The Name$ , " . " ) ' check far an ext ens ion. then
If Peri ad% Then ' co nstr uct the name.
BakNa me Left$(The Nam e$, Pe riod %) + "BA K"
El se
BakName TheName$ + ".BAK"
End I f
' Create a . BAK f i le befare lo ading record s.
If TheName$ = "" Or Bak Name = "" Then Exit Sub
Result% = CopyFile(T heName$, BakName$, RANDOMFILE)
' If there was a prob l em. warn t he user.
If Result% <> Tru e Then
BakName = ""
MsgBox ( "Cou ld n ' t c reate . BAK file " )
End I f
FileNum% = FileOpener(TheName$, RA NDOMFILE. Len(RecordVar)l
If Fil eNum% Then ' Initialize the globals.
WorkingF ile Num = FileNu m%
Wor kingFil eName = TheNa me$
RecordNumber = 1
Po sition = 1
La stRecord = LOF( WorkingFileNum) \ Len(Record Var )
ShowRecord ' Di splay record, t hen turn
TempFileFlag = False ' off Te mp Fil e Flag.
End I f
End If
Forml.Caption "Rec ord Edito r : " + Worki ngFi l eName
End Sub

If th e attempt to open th e file succeeds, the global variables Wo r k in g Fil e Num,


Work i ngFi l e Name, Record Numb er, and LastRecord are ass igned proper values. The
Temp Fil e Flag is set to Fa lse. Finally , the name of the fil e is disp layed in the title bar.

Microsoft Visual Basic Programmer's Guide


Chapter 21 Processing Files 343

Reading and Writing Data: The CheckEmOut Procedure


Using the technique outlined in the preceding section for calculating the number of records
in a random-access file, you can write code to read all the records in the file. Note that it is
not necessary to close a random-access file between read and write operations, as is true
with the sequentially accessed file. The NextRecord_Click and PreviousRecord_Click
procedures are invoked when the user chooses the Next Record or Previous Record buttons.
Both procedures first call the following CheckEmOut Function procedure, and if the fields
in the current record have been changed since being displayed, the user is given a chance to
store or discard the changes.
Function CheckEmüut () As Integer
For Ind% = 0 To NumBoxes% - 1
If FieldBoxes(Ind%).Text <> "" Then ' Does box contain text?
CurrentContents$ = LTrim$(RTrim$(FieldBoxes(Ind%).Text))
PriorContents$ = LTrim$(RTrim$(OldContents(Ind%)))
If CurrentContents$ = PriorCo ntents$ Then SameText% = SameText% + 1
El se
EmptyBoxes - EmptyBoxes + 1
End I f
Next Ind%
If EmptyBoxes - NumBo xes% Then CheckEmüut - 0 : Exit Fu nct io n
If SameText% <> NumBoxes% Then
Ms g$ - "Would you like this record stored now?"
An swer% = MsgBox(Msg$, 52, "Store Now?")
lf An swer% - 6 Then ' Define YESVAL% as 6, then use here .
I f Position = 0 Then Position - 1
Reco rdVar.Fir s tName - FieldBoxes(0).Text
Reco rdVar.LastName = FieldBoxes(l).Text
Rec ordVar.Salary = Val(FieldBoxes(2).Text)
Reco rdVar.Age = Val(FieldBoxes(3).Text)
Rec ordVar.Gender = FieldBoxes(4).Text
If NewRecordFlag Then ' If record is new, put it at end of fil e_
LastRecord - LastRecord + 1
RecordVar.RecordNum - LastRecord
Put #WorkingFileNum%, LastRecord, RecordVar
NewRecordFlag - False
El s e ' _Qtherwise, just replace it with new data .
Record Var.RecordNum = RecordNumber
Put #WorkingFileNum%, RecordNumber, RecordVar
End I f
ShowRe cord 'Note : if it is a new record,
CheckEmüut 1 ' ShowR ecord wi l l show the one
El s e ' current when the user chose
Chec kEmOut 0 ' Add Record.
End I f
End I f
End Fun ct i on

Microsoft Visual Basic Programmer's Guide


Part 4 Advanced Applications

The NextRecord Click Procedure


When Check.EmOut returns to NextRecord_Click, Pos i ti on is incremented if it does not
airead y represent the last record ; Show Record then displays the record. If Pos i ti on equals
LastRecord, a message is displayed indicating the current record is the last record .
Sub NextRecord_Click ()
If La stRecord <> 1 Then ' If this isn't on ly record,
RecordWasStored% = CheckE mOut( ) ' see if it needs to be stored .
End I f
If Position < LastRecord Then ' If it's not the last record
Position = Position + 1 ' in crement Position and di splay
ShowRecord ' the record: otherwi se tell
Elseif Position = LastRecord Then ' user it is last record.
Msg$ = "Thi s is the last record in the file. Choose Add "
Msg$ - Msg$ + " Record if you'd like to add a new record now."
MsgBox (Msg$)

End If
· If user decided not to add a new record turn the flag off .
If NewRecordFlag Then NewRecordFlag = False

End Sub

The PreviousRecord Click Procedure


The procedure PreviousRecord_Click is essentially the same as NextRecord_Click, but the
logic is reversed:
Sub PreviousRecord_Click ()
Answer% = CheckEmOut( l
If Position > 1 Then
Pos i tion = Position - 1
ShowRecord
Elself Position = 1 Then
Msg$ = "Thi s is the first record in the file. Choose Next "
Msg$ = Msg$ + " Record if you 'd like to see other records now . "
MsgBox (Msg$)
End If

' lf user didn't add new record, turn flag off .


If NewRecordFlag Then NewRecordFlag = False
End Sub

M icrosoft Visual Basic Programmer's Guide


Chapter 21 Processing Files 345

The AddRecord_Click Procedure


The AddRecord_Click procedure is in voked when the user chooses the Add Record button.
The record isn't actually placed in the file in this procedure. It simply checks to see if the
current fields need to be saved, then calls ClearFields to prepare the fields for accepting new
data. The NewReco rd Flag is set to True. lf the user tries to exit, open a new file , or move
forward or backward in the records , the CheckEmOut procedure prompts whether or not to
store the record at that time.
Sub AddRecord_Click ()
Result = CheckEmüut()
Cl earFie lds
NewRecordFlag = Tru e
FieldBoxes(0).SetFocu s
End Sub

Sub ClearF ield s ()


FieldBoxes(0).Te xt
FieldBoxes(l).Te xt
FieldBoxes(2). Text
FieldBoxes(3).Te xt
FieldBoxes(4) . Text
End Sub

The DeleteRecord Click Procedure


The DeleteRecord_Click procedure is tricky. The algorithm involves getting the data of the
record following the one to be del eted , then writing its data over that of the record to be
del eted. This results in the loss of th e data of the deleted record. However, the data wit h
which the deleted record was overwritten remains in the next record, so you must ge l the
data from the record followin g it and overw1ite it. You proceed ali the way throu gh th e fil e
doin g the same thing with eac h succeeding record .
Finally, ali the records in the fil e that followed the one to be deleted have been moved
forward one posi tion . Howeve r, the number of records remains the same and the data of the
penultimate record is duplicated in the last record . If you delete another record, the sa me
thing happens, leaving two duplicate records at the end of the file , and so forth. However,
each time a record is deleted, the global variable Las t Re e o rd is decremented, so the
duplicate records at the e nd of the file are inaccessible. If new records are added , th ey
simply overwrite the deleted duplicares at the end of the file .

Microsoft Visual Basic Programmer's Guide


346 Part 4 Advanced Applications

Sub DeleteRecord_Click ()
Start with file position of the currently displayed record
(Posi tion) and copy each RecordNumber+l to RecordNumber .
' This leaves a duplicate of the last record at end of the file,
so reset LastRecord to LastRecord - 1. When user exits,
' any duplicate records are expunged using CleanUpFile.
Dim TempVar As RecordType
If Position = LastRecord And LastRecord = 1 Then
Msg$ "Thi s is the last record in the file . Deleting it will destroy"
Ms g$ Msg $ +" the whole file."
Msg $ Msg$ + " Record Editor will also be closed."
Msg$ Msg$ + "Choose OK to destroy file"
If Msg8ox(Msg$, 65, "About to delete file!")= 1 Then
Clas e
Work ingFileNum = 0
TempFileFlag = 0
Ki l l Worki ngFi l eName
WorkingFileName
Cle arFields
End If
End
End If
For Ind% = Po s iti on To LastRecord - 1
Get #WorkingFileNum, Ind% + 1, TempVar
Temp Var.RecordNum = Ind%
Put #WorkingFileNum, Ind%, TempVar
Next I nd%
LastRecor d = LastRecord - 1
ShowRe co rd ' Note thi s display s record
En d Sub ' following deleted record .

lt is crucial to assign the old record number to each new occupant of each position. In the
DeleteRecord_Click procedure, this was done with the statement RecordVar RecordNum
In d% beca use In d %represents the true current position of the record in the file .

The ExitButton_Click, WriteOuery, and CleanUpFile Procedures


The ExitButton_Click procedure starts by checking to see if the current record needs to be
stored. The n it determines whether the file is a temporary or permanent file . lf the former, it
querie s the user whether or not to save the file , prompting for a permanent name . lf a
permanent name is g iven , it is placed in the argument NewFileName$ in the WriteQuery
Function procedure. lf the user decides not to save the temporary file , it is deleted, and the
fl ag Write I t$ is set to False. If the file is a permanent file , the same query is initiated .
However, if the user doe s not want to save the current state of the record s, the old state of
the rile is restored by deleting the file with the name WorkingFileNam e, opening a new file
with th at name , th en copying the contents of the .BAK file into the new file named
Workin g FileNam e.

Microsoft Visual Basic Programmer's Guide


Chapter 21 Processing Files 347

Sub ExitButton_Click ()
RecordWasStored% = CheckEmOut()
If TempFi leFlag = True Then
' Ask if user wants to save records to a permanent file ...
If WriteQuery(NewFileName$) = True Then
Writelt% = True ' If so, set flag True.
Else ' Otherwise close all files and
Close ' delete the temporary file, then
Kill Wor kingFile Name ' set the flag to False.
Writelt% = False
End If ' If it wa sn ' t a temporary file,
El se ' see if user want s to sa ve it.
If WriteQuery(NewFileName$) True Then
Writelt% = True ' If so , set flag to True .
Else ' If user doesn 't want to save ...
If BakName <> "" Then
Close ' ... el ose all file s, then delete the file
Kill ijorkingFileName ' befare rewriting it with BAK file contents.
Result% = CopyFile(BakName, WorkingFileNam e, RANOOMFILE)
End If
End I f
End I f
If Writeit% = True Then ' If records are to be sa ved,
CleanUpFile (Ne wFil eName$) ' pass NewFil eName$ (recei ved from
End I f ' Wri teOuery ). and el ean i t up.
Close ' Dn close. anything not written to di sk is wr itten to disk .
End
End Sub

Funct ion Writ eü uery (NewFileName As St ring) As Inte ger


Msg$ = "D o you want to sa ve these records to a fil e? "
If MsgBox(Msg$, 65, "Save these records?") 1 Then
GetName "Save As:"
NewFileName$ = WorkingFileName
If NewFil e Name$ = "" Then WriteQuery = Fal se: Exit Function
' If file doesn't exist, return True
If ConfirmFi le(NewFi leName$, RANOOMFILE) = 0 Then
Writeüuery = True
El se ' Otherwise, see if it's OK to overwrit e it . ret urn response.
Msg$ = "Th e ol d " + NewFi l eName$ + " wi 11 be overwri tten ! "
If MsgBox(Msg$, 49, "OverWriting old file" )= 1 The n
Writeüuery = True
End I f
End I f
El se
Writ eüuery Fal se
End I f
End Function

Microsoft Visual Basic Pro grammer's Guide


348 Part 4 Adv an ced App lication s

T he way seq ue nti al-fil e access was used in the Tex t Edi tor applicati o n, w he n th e state o f th e
rnul ti line tex t box was saved, the old fi le was overwritten. Because ali the edits to be saved
were in the text box, overwriting the old fi le was the o nl y thin g necessa ry to rn ake the state
of th e fil e the sarne as the state of the tex t box. W ith a rando rn- access fil e, the same is true
whe n a record is changed, then sto reddvbpga path at record overwrites the prev ious record
hav ing the sarne number. When a record is added, it is appended to the end of the file by
givin g it a record nurnber o ne g reater th an th e prev ious La s tR ec ord number. However,
when a reco rd is de leted , it is possible to have old record s still in the fil e, thou gh
inaccess ible.
In the Exi tButto n_C lick procedure, possible dupl icate record s are ex punged permanentl y
fro m the fi le by callin g CleanUpFile. It creates a tem porary fil e containing o nly valid
records, then deletes th e old record fi le, ope ning a new fil e w ith the name of the old record
fi le, and copy in g th e record s fro m th e te mporary file to the new fil e with the old fil ename.
Sub CleanUpFile (NewFileName As String)
CleanF i le Num% = Fil e0 pener( "- T2m3p 7-.Tmp " , RAND OMFILE, Len(Reco r dVar))
Far Ind& = 1 To Last Record
' Place all vali d r eco r ds (i.e. thase preceding LastRecard)
' in a temparary f i le .
Get #WarkingFileNum, Ind&, RecordVar
Put #CleanFileNum%, Ind&, RecordV ar
Next I nd&
Clase WarkingFileNum% · Clase bath files. If it was a temp
Clase CleanF i leNum% · ar renamed file. use CapyFile.
If TempFileFlag Or (UCase$(WarkingF ile Name) <> UCase$(NewFileName$)) Then
Resul t% = CapyFi le( "-T2m3p7-. Tmp", NewFi l eName$. RANDOMFILE)
Kill "-T2 m3p 7-.Tmp "
Else
' Otherwise. if it is justa file being cleaned up, but not renamed,
' delete original file, and rename the temp file with orig inal name.
Kill WarkingFileName
Name "-T2m3p7-.Tmp " As WarkingFi leName
End I f
End Sub

Using Record Numbers to Retrieve Records


As illustrated in th e precedin g secti ons, you can read any reco rd fro rn a rand o m-access fil e
by specify in g the record 's number in a Get sta tement. Yo u ca n write to any record in a
ra nd o rn -access fi le by spec ify ing th e record 's number in a Put state ment. T hi s is one of the
major adva nt ages that randorn-access fi les have over sequen ti a l fil es. because seq uenti al
fil es do no t permit direc t access to a spec ific record.

Microso ft Visua l Basic Programmer's Guide


Chapter 21 Processing Files 349

So far, finding a specific record using Record Editor is a matter of stepping past each one
with the Next Record or Previous Record buttons, until you find the one you want. You can
change this so the Record Editor can skip among records, displaying any record without
stepping past the others individually. Far example, add a horizontal scroll bar to the bottom
of the form, as shown in Figure 2 1.4, and set its Ct!Name property to HScroller.

11 Record Editor: "Tmp0212.022 ªª


11
First Name Last Name
---~¡
S-alal)'. I~ Ag~ D S~x D
1 Next Record 11Previous Record I p_pen Fil~

1 Add Record 11 De lete Record 11 Exit 1

Sera// bar
Figure 21.4 Adding a horizontal scroll bar to Record Editor

The code far the HScroller_Change procedure is:


Sub HScroller_Chang e ()
' See if scro ll bar valu es need updating .
Scro l ler Update
' See if a record needs storing.
RecordStored% = CheckEmO ut( )
' Set position of record to display.
Position = HScroller.Value
· Display it.
ShowRecord
End Sub

T he first call is to a procedure that updates the scroll bar:


Sub ScrollerUpdate ()
I f LastRecord <> 0 Then
' Updat e the sc r oll bar properties.
HScroller.Max = LastRecord
HScroller.min = 1
HScro ll er.S mall Change = 1
HScrol l er.LargeChange = Int((LastRecord \ 10) + 1)
If HScroller.Value > LastRecord Th en HScro ller.Valu e LastRecord
End I f
End Sub

Microsoft Visual Basic Programmer's Guide


350 Part 4 Advanced Application s

In addition to calling the ScrollerUpdate Sub procedure from HScroller_Change, you will
have to call it from the Form_Load procedure to initialize the scroll bar, as well as the
NextRecord_Click and PreviousRecord_C lick procedures, which are often called after a
record is added or deleted. Also, add this line at the end of the NextRecord_Click and
PreviousRecord_ Click procedures:
HScrol l e r . Valu e = RecordNumber

Thi s will keep the scroll box on the scroll bar positioned correctly when the user moves
among records using the Next Record and Previous Record command buttons. There is no
need to update the scroll bar when the user deletes a record or adds a record, because
Re cord Number does not change in ei ther of those situations. The only change is to the data
to which the record number refers. LastRecord is altered, but the next time the scroll bars
change, these new values are taken into account.

Binary File 1/0


Binary access is a third waydvbpgapain addition to random access and sequential
accessdvbpgapato read or write a file' s data. Use this syntax to open a file for binary I/0 :
Open fi le$ For Binary As# filenumber%

Binary access is a way to get at the raw bytes of any file , not just ASCII- or ANSI-form al
text files. This makes it very useful for reading or modifying files saved in other formats,
such as Microsoft Word files or executable files.
Files opened for binary access are treated asan unformatted sequence of bytes. Although
you can read or write a record (a variable declared as having a user-defi ned type) to a fil e
opened in the Binary mode, the fil e itself does not have to be organized into fixed-len gth
records. In fac t, binary 1/0 does not have to deal with records at ali, unless you consider
eac h byte in a file as a separare record.

Comparing Binary Access and Random Access


The Binary mode is simil ar to the Random mode in that you can both read from and write
to a file after a single Open statement. (Binary access thus differs from sequential access,
where you must first clase a file and then reopen it if you want to switch between reading
and writing.) Also, like random access, binary access lets you move backward and forward
within an open file. Binary access even supports the same statements used for reading ancl
writing random-access files using thi s syntax:
{Get I Put} # fi/enumber % , [position&], variable

Here, variable can have any type, including a variable-length strin g ora user-defined type,
ancl positio11& points to the place in the fil e where the next Get or Put operation will take
place. (The value of position& is relative to the beginning of the fil e; that is, the first byte in 1
the fil e has position one, the second byte has position two, and so on.) If you leave off
position& , successive Get and Put operations move the file pointer sequ entially throu gh the
file from th e first by te to the las t.

Microsoft Visual Basic Programmer's Guide


Chapter 21 Processing Files 351

The Get statement reads a number of bytes from the file equal to the length variable.
Similarly, the Put statement writes a number of bytes to the file equal to the length variable .
For example, if variable has the integer type, Get reads two bytes into variable; if variable
has the single-precision type, Get reads four bytes. Therefore, if you don't specify position
in a Get or Put statement, the file pointer is moved a distance equal to the length variable.
The Get statement and Input$ function are the only ways to read data from a file opened in
Binary mode. Put is the only way to write data to a file opened in Binary mode.
Binary access, unlike random access, enables you to move to any byte position in a _file and
then read or write any number of bytes you want. In contrast, random access can only move
to a record boundary and read a fixed number of bytes (the length of a record) each time.

Example In the following example the CopyFile Function procedure used in Record Editor is
rewritten using binary access, as BinaryCopy. Because it simply makes a byte-for-byte copy
of the file to be duplicated, you can use this procedure for any file, regardless of the type of
access normally used. For example, the procedure could be used in Record Editor, in place
of CopyFile. Because the variable used in the transfer is an integer, the bytes are transferred
two ata time, which is why the loop proceeds with a Step 2.
Function BinaryCopy(Namel As String. Name2 As String) As Integer
On Error Goto BinaryCopyHandler
Name1Num% = FileOpener(Namel. BINARYFILE. 0)
Name2Num% = FileOpener(Name2, BINARYFILE. 0)
If Name1Num% <> 0 and Name2Num% <> 0 Then
Filelen& = LOF(Name1Num%)
For Ind& = 1 to Filelen& Step 2
Get #Name1Num%, Ind&.Holder %
Put #Name2Num%. Ind&.Holder%
Nex t Ind&
Binary Co py = True
El se
BinaryCopy = False
End If
Exit Fun ction
BinaryCopyHandler:
Action% = FileErrors(Err)
Select Ca s e Action%
Case 0
Res ume
Case 1
Res ume Ne xt
Case 2
BinaryCopy - False
Exit Function
Ca se Else
Error Err
End Se l ec t
End Funct i on

Microsoft Visual Basic Programmer's Guide


352 Part 4 Advanced Applications

Note that the record length argument used with Fileüpener is zero. With binary files, the
record length is not used . Even if it is specified in the Open statement, it is ignored .

Positioning the File Pointer with Seek


lf you want to move the file pointer to a certain place in a file without actually performing
any 1/0, use the Seek statement. Its syntax is :
Seek [#]fi/enumbero/o, position&

After a Seek statement, the next read or write operation in the file opened withfilenwnbero/o
begins at the byte noted in position& .
The counterpart to the Seek statement is the Seek function , which uses thi s syntax:
Seek (file11111 11bero/c )

The Seek functi on tells you the byte position where the very next read or write operation
begins . (lf you are using binary VO to access a file , the Loe and Seek function s give similar
res ult s, but Loe returns the position of the last byte read or written, while Seek return s the
position of the nex t byte to be read or written .)

Seek with Sequential- and Random-Access Files


T he Seek stateme nt and function also work on file s opened for seguential or random access.
With seguential access, the statement and the function behave in the same way they do with
bin ary access; th at is, the Seek statement moves the fil e pointer to a spec ific byte position,
and the Seek fun ction returns information about the next byte to read or write.
1lllweve r. if a file is o pened for random access, the Seek s tatement can move the fil e po inter
onl y 10 th e beginn in g of a record , not to a byte within a record . Also, when used with
random-access files, the Seek function return s the numbe r of the nex t reco rd rath er th an the
posi1 ion of the next byte.
With so me experimentation , you can use binary access to create files with format s spec ific
to yo ur ow n programs. For example, you co uld di vide a fi le into two or more sec tion s. the
las l of which has va riable length, and those preceding it having fixed len gth . The fixed
length sec tion s could then contain information about the variabl e- length section s. For
exa mple, you mi ght want to encrypt a file , storing the encryptin g information in a fixed -
le ng th sec tion at the beginning of the file , and the encrypted information in the variable-
le ngt h section. Th en, only programs possessin g knowled ge of the file structure could read
th e info rm ation in the file .

Microsoft Visual Basic Pro grammer's Guide


Communicating with Other Applications

One of the most powerful aspects of the Microsoft Windows and Presentation Manager
operating environments (compared with earlier operating systems) is the ease with which
data can be shared among applications. In Chapter 18, "Interacting with the Environment,"
you saw that Visual Basic applications can use the Clipboard to share data with other
Windows or Presentation Manager applications.
But Visual Basic provides capabilities that go farther than that. Vi sual Basic implements
dynamic data exchange (DDE), a standard method for transferring data between applications
runnin g in the operating environment. Using DDE, your Vi sual Basic applications can
automatically obtain data from other applications, whenever that data changes, without
requiring any work on the part of the user. Similarly, Visual Bas ic applications can provide
data - such as commands and even individual keystroke input - to other running

..-.
···-··.
. • ••
applications on an ongoing basis. This gives your Visual Basic application the ability to
comrnunicate with any running program.
The main sections in this chapter are:
• What Is Dynamic Data Exchange?
• Creating Links at Design Time
• Link Properties




Link Events
E nabling Users to Create Their Own Hot Links
Using Methods to Perform DDE Operations
Handling Errors
•• -- •• •
••••
• Sending Key strokes to Other Applications

•••

••

••

11
• •
• •
354 Part 4 Advanced Applications

What Is Dynamic Data Exchange?


Dynamic data exchange is a mechanism supported by the Microsoft Windows and
Presentation Manager operating environments that enables two applications to "talk" to each
other by continuously and automatically exchanging data. DDE automates the manual
cutting and pasting of data between applications, providing a faster vehicle for updating
information.

Note Not all applications support DDE. Consult the documentation for your other
applications to see if they support DDE.

Clients, Servers, and Conversations


Two applications exchange information by engaging in a DDE conversation. This is similar
to a conversation between two people. The application that initiates the conversation is
called the client application , or just the client ; the application responding to the client is the
server application, or just the server. An application can be engaged in several
conversations at the same time, acting as the client in sorne and the server in others. There is
nothing special about an application that makes it a client or server; these are simply roles
that an application can adopt.
In Visual Basic, any text box, picture box, or !abe! can be the client in a conversation, while
any form can be a server.

Applications, Tapies, and ltems


When a client application begins a DDE conversation, it must specify two things:
• The name of the server application it wants to talk to.
• The subject of the conversation, called the topic.

When a server application receives a request for a conversation concerning a tapie it


recognizes, it responds and a conversation is started. Once established, a conversation cannot
change applications or tapies. The combination of application and tapie uniquely identifies
the conversation, and it remains constant for the duration of the conversation. If either the
client or the server changes the application or the tapie, the conversation is terminated.
During the conversation, the client and server may exchange information concerning one or
more items. Items are references to data that is meaningful to both applications. Either the
client or the server can change the item without affecting the state of the conversation.
Together, the application, tapie, and item serve to uniquely identify the data that is being
passed between the applications. Each of these is discussed in detail in the sections that
follow.

l
Microsoft Visual Basic Programmer's Guide
Chapter 22 Communicating with Other Applications 355

Application Name
Every application that can be a DDE server has a unique application name. Usually this is
the executable filename without any extension. The names of a few Microsoft applications
are shown in the following table.
Application DDE application name
Microsoft Excel Excel
Microsoft Word for Windows WinWord
Microsoft Word for Presentation Manager PMWord

When a form in a Visual Basic application is the server in a conversation, its application
name is the name you choose for the application when you make it into an executable file . If
you are running your application within Visual Basic. the application nam e is the name of
the project without any file extension.

Note For the application name of other Windows applications, see the documentation for
those applications.

Topic
The tapie defines the subject of a DDE conversation and is usually sorne unit of data that is
meaningfu l to the server application. Most applications recognize a document name as a
tapie for a DDE conversation. For example, Microsoft Excel recognizes a filename
(including the path if necessary) ending in .XLS or .XLC, while Word recognizes a filenam e
ending in .DOC.
When a form in a Visual Basic application is the server in the conversation, you can specify
the tapi e by setting the LinkTopic property for the form. The LinkTopic property is
described later in this chapter in the section "Link Properties."
Many app lications that perform DDE support a tapie called "System." You can use this tapie
to request information from the application (what other tapies it supports, what data formats
it supports, and so on). Check the documentation for the application to see if it supports this
tapie.

ltem
The item identifies the piece of data actually being passed during the DDE conversation. For
example, Excel recognizes cell references (such as RlCl) as items in a conversation.
When a co ntrol in a Visual Basic application is the client in a conversation, it defines the
ítem for the conversation by setting the Linkltem property for that control. The Link.Item
property is described later in this chapter in the section "Link Properties."
When a form in a Visual Basic application is the server in a conversation, the name of each
of the text boxes, label s, and pictures on the form can be the itero for a DDE conversation .

Microsoft Visual Basic Programmer's Guide


356 Part 4 Advan ced Application s

Links
A DDE conversation is often called a link because the two applications in the conversation
are linked by the data they are exchanging. There are two kinds of links, distinguished by
how the server updates the client when data in the server changes:
• Hot link: The server supplies new data to the client every time the data defined by the
Linkltem changes.
• Cold link: The server supplies new data only when the client requests it.

Creating Links at Design Time


While you are designing a Visual Basic application, you can create data links between it and
other app li cati ons th at suppo rt DDE. These links are sa ved as values in the various Link
properties of the forms and controls in your application, so that they are automatically
re-established whenever the application is mn . This is convenient, because you don't have to
write any code to allow your applications to perform DDE conversations with other
applications. However, this convenience comes at the expense of sorne flexibility, because
you cannot change these links without writing code to do so.

Obtaining Data Through Links


If you want your Visual Basic application to use data supplied by other applications, then
you want to create a client link. A client link is one in which your application (the client) is
th e one requestin g the information , and the other application is the server. You can create
such a link at desi g n time and make ita permanent part of your application. To do this , you
must have the project containing your ap pli cat ion open in the Visual Basic environment , and
the other application must be runnin g.

To create a client link between your application and another application:


1 In the other application, select the data item you want to link.
2 From the Edit menu in that application, choose the Copy command.
3 In your Visual Basic application, select the control (text box , label , or picture box) that
you want to receive the data.
4 From the Edit menu in Visual Basic, choose Paste Link.

If the link is successful, the contents of the control (the Text property of a text box, the
Caption of a label , or the Picture of a picture box) change to display the cuITent state of the
data in the server application. If the Paste Link command on the Edit menu is unavailable,
then the server application you attempted to paste the link from does not support DDE, or
cannot provide data in a format that Visual Basic recognizes .
Remember that this is a hot link; once the link is established, the contents of the control will
l
change whenever the data in the server application changes. This will happen whi le yo ur '
application is running (causing a Change event) and whi le you're building the application ,
so don 't be surprised if you see the contents of controls changing at design time.

Microso ft Visual Basic Programmer's Guide


Chapter 22 Commun icating with 0ther Applications 357

This link is saved wi th the form and is "permanent. " Whenever the application is opened (in
des ign time as we ll as run time) , it attempts to re-establish the conversation with the server
a pplicati o n.

Note W hen a Visual Basic application containing hot links is opened or run , Vi sual B asic
checks to see if there are any server applications running that recognize the topic of the
conversatio n. lf there is another application that recognizes the topic , Visual Basic
esta bli shes the conversation. If no application responds , Visual Basic di splays a message
askin g the user i f it should attempt to start the other application . If the user chooses Yes,
Visual Basic atte mpts to run the application , with the spec ified topi c .

Providing Data Through Links


lf yo u want yo ur V isual Basic application to supply data to other application s, the n yo u wa nt
to create a se rver link. A server link is one in which the other application (the clie nt)
requests data from yo ur application (the server). Like client hot links, you can create serve r
hot links at des ign time and make them a permanent part of your application . To do thi s, yo u
must have the project containing your application open in the Visual Basic environm en t, and
the other appli cati on mu st be running.

To create a server link between your application and another application:


1 In yo ur V isual Basic app li cation , select the control that contains the data you wa nt to
suppl y.
2 From the Ed it menu in Visual Basic, choose the Copy command .
3 In th e c li e nt app li ca ti on , se lect the destination for the data .
4 From th e Ed it menu in the c li ent app li cation , choose Paste Link.

If the lin k is s uccessful , the contents of the control (the Text property of a tex t bo x, the
Caption of a label , or the Picture of a picture box) are di spl ayed in the cli ent ap plica ti on. lf
there is no Paste Link co mmand in the cli ent application , th en it does not support DDE hot
links. If the Pas te Link comm and ex ists but is unavailabl e, then the c li ent does not recog ni ze
the data you attempted to suppl y from your Visual Basic appli cati on . Many a ppli catio ns do
not recogni ze picture d ata, for example, and sorne restrict the kind of info rmati o n that can
appear in certain parts of their documents. Consult the documentation for the cli ent
application if thi s is the case.
Once yo u ha ve establi shed a hot link between a contro l in your appli cati on anda client
appli catio n, V isual Basic autom aticall y suppli es new data to the cli ent appli ca ti on every tim e
the contents of the control change. You can change the co ntents of th e co ntrol at design tim e
and watch as Visua l Basic suppli es the new data to the other appli cation.
However, w hen yo u run yo ur app li cati on Visual Basic mu st break the links as it sw itches
from des ig n time to run tim e . Sorne app li cati ons handl e thi s and auto mati call y at te mpt to re-
estab li sh the ir DDE co nversati ons, but you may find that the serve r links you esta bli shed at
design tim e no lon ger work at run tim e . Most app li cati o ns that suppo rt DDE provide sorne
way to refres h the ir links manuall y ; consult the docum entation for that application .

Micro soft Visual Basic Programmer's Guide


358 Part 4 Advanced Applications

Link Properties
Us ing the Copy and Paste Link commands to establish DDE conversations is fine for quick
programming tasks, but they aren't flexible enough for most sophisticated applications. In
add ition , they don ' t enable you to set up conversations with other applications that support
DDE but do not provide Copy and Paste Link commands.
To go further with DDE in Vi sual Basicdvbpgapato create and use DDE conversation s from
code, orto manu all y establish conversations without using Paste Linkdvbpgapayou mu st
exp lore and use the Link properties of forms and controls.

Client Link Properties


C li e nt lin ks are maintained by properties on the control th at is th e cli ent of th e conversation .
To ex pl ore these properties, look at what the Visual Basic Paste Link com mand actuall y
does. When you perform a Paste Link on a control to make it the client of a DDE
conversation, Visual Basic actually sets the values of three of the properties for that control:
LinkTopic , Linkltem, and LinkMode.

The LinkTopic Property


The LinkTopic property of a control specifies its DDE conversation . When a control is
engaged in a DDE conversation with another application, the LinkTopic property contains
the name of that applica tion and the topic of the conversation using this convention :
Applica tion ITopic

Th e nam e o f th e se rver application is separated from the topic by a vert ical bar or " pipe·'
character (c haracter code 124). For example, a link with a Microsoft Exce l spreadsheet
mi g ht loo k like th is:
Ex ce llc:\exce l\pay .x Is

You can ~et thi s property for any text box , !abe! , or picture cont ro l. Jf you know the
appl ica ti on na me for an app li cation , and a topic ii: support s, you can establi sh a DD E
con ve rsa tion w ith that applicati on .

The Linkltem Property


Th e Link ltem prope rt y of a control specifies the item for the co nversation defined by th e
LinkTop ic property for that control. The se ttin g of thi s property va ri es depending on th e
ser ve r a ppl ica ti on. For example, if the topic of a conversa ti o n w ith Microsoft Exce l is a
spreadsh ee t, th e Li nkltem co ul d be :
RI C I

Microsoft Visual Basic Programmer's Cuide


Chapter 22 Communicating with Other Applications 359

The LinkMode Property


If you try setting the LinkTopic and Linkltem properties, you'll find that nothing happens .
This is because you have to "actívate" the link by setting the LinkMode property to Hot (1)
or Cold (2). Normally, the LinkMode property for a control is set to None (0) . When it is set
to Hot or Cold, Visual Basic immediately attempts to initiate the conversation specified in
the LinkTopic property. If the server application specified in the LinkTopic property is not
running, Visual Basic displays a message asking if you want to start that application.
As long as the LinkMode property is set to Hot, Visual Basic maintains the conversation.
This is a hot link, so whenever the data specified by the combination of the LinkTopic and
the Linkltem changes, the control receives the new data and a Change event is generated for
that control. You can termínate the conversation at any time by setting the LinkMode
property to None.
If you change the value of the LinkTopic property, Visual Basic terminates the old
conversation. It 's good practice to set LinkMode to None before changing the LinkTopic
property . Once you have set the new value for LinkTopic, you can establish the new
conversation by setti ng LinkMode to Hot or·Cold again.

Note If the server application terminates a conversation, the LinkMode property is not set
to None. Instead, a LinkClose event (described later in "Link Events") occurs, but the
LinkMode property retains its value. Once the conversation is terrninated, performing any
DDE operation on this link causes a run-time error.

Example The following code for a form Click event attempts to establish a hot link conversation
between a text box on the form and Microsoft Excel when the form is clicked the first tim e.
Each time the form is clicked after that, the item for the conversation is changed (notice that
this <loes not terminate the conversation):
Sub Form_Click ()
Const HOT = l. NONE = 0
Static Row as integer
Row = Row + 1
If Row = 1 Then
Textl.LinkMode = NONE
Textl.LinkTopic = "E xce l Jc:\excel\amortize.xls"
Textl . Linkltem "RlCl"
Textl.LinkMode HOT
El se
Textl. Li nkltem "R" + LTrim$(Str$(Row)) + "Cl"
End I f
End Sub

Note The co nstants HOT, NONE, COLD, and SERVER, and the constants for the various
DDE error values, are contained in the CONSTANT.TXT file . You can use these constants
in your code if you load this file into the global module for your application .

Microsoft Visual Basic Programmer's Guide


360 Part 4 Advanced Applications

You also ca n se l lhe LinkMode property to Cold (2). When LinkMode is Cold, a
conversat ion ex isls, but the control does not automatically receive new data whenever il
changes . To obtain the most up-to-date data, you must use the LinkRequest method on the
co ntrol.
Example The fo llowing code for a form Click event attempts to establish a warm link conversation
betwee n a tex t box on the form and Microsoft Excel when the form is clicked the first tim e.
Each time the form is clicked after that, new data is requested:
Sub Textl _Click ( )
Const CO LO = 2, NONE = 0
If Textl .LinkMode = NONE Then
Textl. LinkTopic = "E xce l lc:\e xcel\ amortiz e.x l s "
Textl.Linkltem "Rl Cl "
Textl.LinkMode = COLO
End 1f
Textl.L inkRequest
End Sub

If th e LinkTopic or Linkltem property is not set to a valid value, then setting LinkMode to
Hot or Cold causes an error.

The LinkTimeOut Property


Sorne app li cation s take longer to respond in DDE conversations than others . If an
app li ca ti on takes too lon g to respond , Visual Basic generates an error. You can adju t how
long Vi sua l Basic waits for a respon se by setting the LinkTimeüut property for a control.
Th e va lu es for the LinkTimeüut property are tenths of seconds; the default value is 50
lenlh s. o r five seconds . This sho uld be adequate for conversations with most appli cations ,
but yo u ca n adju st itas necessary . This property is meas ured in absolute time , so you ma y
nced lo inc rease this value on slower computers.
1f you se l the LinkTimeüut property to - 1. Visual Basic does not generate a time-out error.
lns lead , it wai ls indefinitel y for the other appl ication to respond .

Note If Vi sual Basic seems to be "hung up" during a DDE conversation , and you don'l
want to wa it for th e time-o ut error to occur (or you have set the LinkTimeüut property to - 1
so il wi ll ncver occur), you can recover by press ing the A LT key. Press ing ALT interrupts any
pend in g DDE operation s in Visual Basic and generates a trappable run-time error.

Server Link Properties


Server links are more co mpl ex th an clienl links because they in vo lve form properties as well
as co ntrol properties.
When yo u co py a control from a forrn in Visual Basic and use Paste Link in another
app li cat ion to estab li sh a conversation with the Visual Basic (server) application , the ot her
(c li e nl ) application initi ates th e co nversation usin g the values of two properti es on lh e form :
LinkTop ic and LinkMode .

Microsoft Visual Ba sic Programmer's Guide


Chapter 'll. Communicating with Other Applications 361

The LinkTopic Property


The LinkTopic property of a form specifies the topic of a DDE conversation the form will
respond to. The names of individual controls on the form define the items that other
applications can use in DDE conversations. The application name is either the application
title you specify when create an executable file (in the Make EXE File dialog), or the project
name (without its file extension) if you are running the app lication in Visual Basic.
For example, if you have a Visual Basic application called Mortgage that contains a form
with a LinkTopic property set to Home, then the application will respond to clients who
attempt to establish this DDE conversation:
Mortgage I Home

If there are controls on the form called Interest, Principal , and Balance, then these are al i
va lid items for this conversation .
If you change the LinkTopic property, Visual Basic terminares ali conversations on that
topic. The client applications can then re-establish links with the new topic.

The LinkMode Property


Like the LinkMode property for controls, the LinkMode property for forms is normally
None (0). When it is None, no client application can initiate a conversation with that formas
the topic.
If LinkMode is set to Server (1 ), the controls on the form supply data to any client that
es tablishes a DDE conversation with them .
Sorne client applications attempt to send data to the se rv er application, even though the flow
of data in DDE conversations is generally from server to c lient. Thi s is called poking data
via DDE. If the LinkMode property for a form is set to Server, it enables client appl ications
to poke data to the control s on th e form; if the LinkMode property is set to None, the form
does not a!low any poking of data to any of the controls on the form.
Example The following code enables you to click the fom1 to set whe th er it responds to DDE
conversations with the topic "Home":
Sub Form_Click ()
Const SERVER = 1, NONE = 0
If LinkMode = NONE Then
LinkTopic = "Home"
LinkMode = SER VER
El se
LinkMode NONE
End I f
End Sub

For more information on the Link properties, see th e Language Reference, or:

m Search Help for:


link

Microsoft Visual Basic Programmer's Guide


362 Part 4 Advanced Applic ations

Link Events
As you might expect, there are events associated with links, and you can write event
procedures to respond to these events. The controls that can be clients in a DDE
conversation recognize these DDE-specific events:
• LinkOpen
• LinkClose
• LinkError

When form s are ac tin g as DDE servers, they recognize these events:
• LinkOpen
• LinkCl ose
• LinkError
• LinkExecute

Client Events
There are three even ts that can only occur when a control is engaged as the client in a DDE
conversation: LinkOpen, LinkC!ose, and LinkError.

The LinkOpen Event


The LinkOpe n event occurs when a co ntrol successfully initiates a DDE conversation . You
can write thi s procedure to respond to the event:
Sub Text l _ Linküpen (C ancel As Inte ger)
Ms g$ = " DDE conv e rsation initiated wi t h LinkTopi c " + Textl .Li nkTopic
Msg$ = Msg$ + " and Linkltem "+ Textl.Linkltem
Ms gBo x Msg$
End Sub

This is useful for deb uggi ng purposes, as in the example above, or whenever you want to
perform sorne opera ti on (suc h as reading a file) every time th e control successfull y initi ates
a DDE conversa ti on.

The LinkClose Event


If a control is engaged in a DDE co nversation and the server terminates the conversation , the
LinkClose eve nt occ urs. You can write an eve nt handlin g procedure that responds to thi s
event. For example :
Sub Textl _ Link Clos e ()
Const NONE = 0
Ms gBo x "D DE s erver terminated co nver satio n. "
Text l. LinkM ode = NONE
End Sub

Microsoft Visua l Basic Programmer's Guide


Chapter 22 Communicating with Other Applications 363

The LinkError Event


If an error occurs when you are using code to manipulate a DDE conversation, it will be a
run-time error that you can trap and handle in the usual way. For more information, see
Chapter 19, "Handling Run-Time Errors."
However, when a DDE conversation is active, errors can occur when no code is executing:
Data may arrive in a format that the client doesn't understand, ora large amount of data may
cause the operating environment to run out of memory. If DDE causes an error to occur
when no code is running, Visual Basic generates a LinkError event. See the section "Error
Handling" later in this chapter for more information.

Server Events
There are four events that can occur only when a form is engaged as the server in a DDE
conversation: Linküpen , LinkClose, LinkError, and LinkExecute.

The LinkOpen Event


The Linküpen event occurs when a client application initiates a conversation . The event
procedure for this event accepts an integer argument, Cancel. The argument is always zero
when the event procedure is called. However, if your event procedure code sets this
argument to True (-1), then Visual Basic won't enable the client application to establish the
conversation. For example, the following code keeps track of how man y clients attempt to
establish DDE conversations, and once the number has exceeded 10 it denies ali further
attempts:
Sub Form_ Linküpen (Cancel as In teger)
Const FALSE = 0, TRUE= Not FALSE
Static ClientCount As Integer
Clie ntCoun t = ClientCount + 1
If Cl ientCount > 10 Then
Cancel - TRUE
End I f
End Sub

The LinkClose Event


The LinkClose event occurs if a client application terminates its conversation . You can write
this code to inform the user when the event occurs:
Sub Form_ LinkClo se ()
Msg$ = "A con ver satio n wa s terminated."
Ms gBox Msg $
End Sub

Microsoft Visual Basic Programmer's Guide


364 Part 4 Advanced Applications

The LinkError Event


As with client links, when code that establishes, terminates, or rnanipul ates a DDE
conversation is exec uting and an error occurs, the standard run-tirne error handler is invoked ,
if there is one. However, DDE can cause errors to occur when no code is executing. If thi s
happens when a forrn is acting as the server in a DDE conversation , Visual Basic generates
the LinkError event for the forrn. See the section "Error Handling" later in thi s chapter for
more information .

The LinkExecute Event


Sorne applica ti ons senda cornmand string to be executed by a server application; thi s causes
a LinkExecute eve nt for a Vi ual Basic form that is acting as a server. The event procedure
for thi s e \·ent accep ts the two arg uments shown in the following tabl e.
Argument Description
CmdStr A string containing the command to be exec uted .
Cancel An integer argument. When a client se nds a comrnand ~o a
server to be executed, it expects to receive either a posi ti ve
ora negative acknowledgement (that is, whether the server
agrees to execute the command). lf Cancel is zero when the
event procedure exits, the client recei ves a positive
acknowledgement; if Cancel is nonzero, the client receives a
negative argument.

Th e contcn ts ol the command string vary from application to application ; there is no


predefi ned lormat or meaning for thi s argument. For example, thi s eve nt procedure accepts a
co rnm and to quit :
Sub Form_LinkExec ute (CmdStr As Str ing, Cancel As Integer )
Const FALSE 0, TRUE= Not FALSE
If CmdStr = " [Ouit] " Then
End
Else
Cancel TRUE
End I f
End Sub

Ir a fom1 has no eve nt proced ure for the LinkExecute event, then when a el ie nt attempts to
se nd a corn mand to the ~orm it always receives a negative acknowledgernent.
For more informat ion on Link events, see the Language Reference, or:

m Search Help for:


link

Microsoft Visual Basic Programmer 's Guide


Chapter 'l1. Communicating with Other Appli cations 365

Enabling Users to Create Their Own Hot Links


Many applicati ons that support DDE prov ide a way for the user to establish DDE
conversati ons without writing code. As you have seen, Visual Basic does thi s with the Copy
and Paste L ink commands on the Edit menu. This is the standard method used by most
applications that support hot links. By writing a little code, you can suppl y thi s feature to th e
users of your Vi sual Basic applications.

Note While you are exploring thi s, you' ll find the Clipboard appli cation (CLIPBRD .EXE)
invaluable. Supplied with your operating environment, it enables you to observe the ac tual
data that your code is placing on the Clipboard.

T he examples in thi s secti on ass um e that yo ur appli ca ti on includes a menu co ntro l array
called MenuB ar that includes an Edit me nu with the usual commands: Cut, Copy, Paste, and
Paste Link .

Adding a Paste Link Command to Your Applications


In applications that support hot links, the Paste Link command enabl es th e user to create
client links that accept data from other applications. A Paste Link command in yo ur
applicati on must obtain link information from the Clipboard and use th at to set the link
properti es of the active control. All applications that support DDE links prov ide link
in fo rm ati on using thi s convention:
Applieation ITap ie!Item

T he Appliccil ion and Tapie are separated by a vertical bar or " pipe" charac tcr (c harac ter code
124 ), and the Tapie and ltem are separated by an exclamation point (c harac te r code 33).
No ti ce that thi s is just an ex tension of the conve ntion used in the L in kTopic property for
co ntrols (described earlier in thi s chapter). Thus, to perform a Paste Lin k opera ti on:
• Obtain the link information from the Clipboard.
• Split the information into a string fo r the applicati on and topic, and a st rin g for the item.
• Use these strings to set the LinkTopic and Linkltem properti es for th e co ntro l th at is
acce pting the Paste Link.
You ca n then determine the active control by using the Acti veContro l prope rty of th e
Screen object.
For more in formati on on the Screen object, see Chapter 18, "Interactin g with the
Enviro nment"; the Language Referenee; or:

m Search Help for:


Scree n object

Microso ft Visual Basic Programmer's Guide


366 Part 4 Advanc ed Applications

The Edit_Click Procedure


This event procedure code implements a Paste Link command:
Sub Edit_C lick (Index As Integer)
Const HOT = 1, CF_ LINK = &HBF00
Select Case Index
Case CUT
' Code to support Edit Cut Comitted).
Case COPY
' Code to support Edit Copy Comitted).
Case PASTE
' Code to support Edit Paste (omitted).
Case PASTEL! NK
Li nk$ = Clipb oard.GetText(CF_ LINK)
ítem% - InStr(Link$, "!")
If ítem% <> 0 Then
Screen. Act i veControl. L i nkMode - NONE
Screen.Act iv eCo ntrol.LinkTopic - Left$(Link$, ítem% - 1)
Screen.ActiveControl.Linkltem = Mid$(Link$, ítem%+ 1)
Screen .Acti veControl. L i nkMode - HOT
Elself InStr(Link$, "I" ) Then
' Sorne DDE links have no ítem.
Screen.ActiveControl . LinkMode = NONE
Screen . ActiveControl .LinkTopic - Link$
Screen.ActiveControl .Lin kltem
Screen.ActiveCont rol.Lin kMode - HOT
End I f
End Select
End Sub

The code assumes th at the constant PASTELJ K is defined in the Declarations section of
the form code and is et equal to the index of the Paste Link menu item .

The MenuBar_Click Procedure


Note that the code for Edit_Click fail s if there isn ' t val id link data on the Clipboard, or if the
active control is not one of the controls that supports DDE. You can modify the code to
check this, but there is a better way . If there isn' t val id link data on the Clipboard, or if the
active control does not support DDE, then the Paste Link command should be made
unavailabl e so the user cannot choose it. To take care of this, use the following code in the
C li ck even t procedure for the menu bar.

Microsoft Visual Basic Programmer's Guide


Chapter 22 Communicating with Other Applications 367

Sub MenuBar_Click (Index As Integer)


Const FALSE= 0 , TRUE= Not FALSE
Const CF_ LINK = &HBF00, CF_DIB - 8, CF_BITMAP - 2 , CF_TEXT - 1
Select Case Index
Case EDITMENU
Edit(PA STELINK).Enabled - FALSE
If Clipboard. GetFormat(CF_ LINK) Then
If Typeüf Sc reen.ActiveControl Is PictureBo x Then
If Clipboard . GetFormat(CF_BITMAP) Then
Edit( PASTELINK).Enabled - TRUE
End I f
Elself Typeüf Scree n. ActiveControl Is TextBo x Then
If Cli pboard.GetFormat(CF_TEXT) Then
Edit(PASTELINK).Enabled = TRUE
End I f
End I f
End I f
End Se l ect
End Sub

This code makes the Paste Link command unavailable if there isn't valid link data on the
Clipboard, or if the active control is nota text box or picture box . You do not have to
consider labels because the user can't select them; thus, a label will never be the active
control.
In addition , thi s code ensures that the Paste Link command is enabled only if the data on the
Clipboard is avail able in a form at appropriate for pasting into the active control: CF_ TEXT
for a tex t box , and CF_BITMAP for a picture box. You also may want to test for CF_DIB
and CF_MET AFILE for a picture box .

Creating Links with the Copy Command


In applications that support hot links, the Copy command allows the user to create server
links th at suppl y data to other applications.
If yo u want to enable users of yo ur application to supply hot-linked data to other
applications, modify the Copy command in your application to place link information on the
Clipboard. In Chapter 18, "Interacting with the Environment," you saw code that copies the
data from the active co ntrol onto the Clipboard. You need to add statements to this code th at
put link information on the Clipboard if the active control is a text box ora picture box (the
controls that support links). Remember, although labels also support links, yo u don ' t need to
add code for them because there 's no way for the user to select a label.
The link information yo u place on the Clipboard must use the same co nvention you saw
earli er:
Application lTop ic!Item

Microsoft Visual Basic Programmer's Guide


368 Part 4 Advanced Applications

For the Application use the project name (if you are runnin g your appli cati on in V isual
Basic) or the appli cati on titl e you provide in the Make EXE File di alog (if you are runni ng
your app lication asan executable fil e). Tapie is the LinkTopic property for th e fo rm , and
It em is the name of the contro l that provi des the data in the link . Because the Ct!Narne
property is not avai lable at run time, you m ust store the nam e of each co ntrol in its Tag
property.
l t is good prac tice to place the ac tu al contents of the contro l (the Text property of a tex t box
or the Pict ure property of a picture box) on the C lipbo ard along with the link in fo rmati on.
You can place m ul tiple pieces of data on the Clipboard as lo ng as you use a d iffere nt forma l
for eac h piece.
Sub Edi t _Click ( Index As Integer)
Select Case Index
Case CU T
' Code to su pport Edit Cut (omitted ).
Case COP Y
Clipboard.Clear
AppTopName$ = App Name() + "I" + LinkTopic
AppTop Name$ = AppTopName$ + "!" + Screen .Acti veContr ol . Tag
If Ty peOf Scree n. Act iv eCo ntrol Is PictureBox Then
Cl ipboard.SetText AppTop Name$, CF_ LINK
Cl ipboard.SetData Sc r ee n . Acti veControl .P i ct ure
Else lf TypeOf Screen.Acti veControl Is TextBox Then
Clip board . SetText AppTo pName$, CF_ LINK
Cli pboard.SetText Sc reen . Activ eCont rol .Text
Elself TypeOf Sc reen.Acti veControl Is CheckBox Then
Clipboard.Se tText St r$(Scre en.ActiveCo ntr ol .Value )
Else
' Copy appropriate data from other types of control s.
End I f
Case PASTE
· Co de to support Ed it Paste (omi t t ed).
Case PASTELINK
· Code to su pport Edit Paste Link (omitted).
End Select
End Sub

T hi s code ass um es the ex istence of a Function procedure call ed App ame that re tu rn s the
na me of the app li cati on. If yo u're ru nning th is code in V isual Basic , th e procedure should
re turn th e name of the projec t without any fil e extensio n. If you are run ni ng an exec utable
file , it sho uld retu rn the appli cation title you prov ide in the Make EXE Fil e dialog .

Note Jf the con tro l th at provides data in the lin k is pa rt of a con tro l array , th en l!em should
inc lude the array index enclosed in parentheses.

Microsoft Visual Basic Programmer's Guide


Chapter 'l2. Communicating with Other Applications 369

Using Methods to Perform DDE Operations


DDE gives you the ability to manipulate other applications by remate control. Once you
have established a client link with another application, you can send data, request data, and
send it commands. When your application is the server in a conversation, you also can notify
the client when data has changed.
You can use these functions and methods to perform DDE operations:
• The Shell function
• The LinkPoke method
• Toe LinkRequest method
• The LinkExecute method
• The LinkSend method

Starting Other Applications


Often, you'll want to establish a conversation with an application that is not currently
running. If you attempt to establish a DDE conversation with an application that is not
currently running, Visual Basic displays a message asking if the user wants to start the
application. Since this might confuse the user, you can trap this like any other run-time error,
and start the application explicitly with the Shell function:

Sub StartApp (L ink As Control. AppName As String, Tapie As String)


On Error Goto StartUp
Link . LinkMode - NONE
Link . LinkTopie - AppName +"l.+ Tapie
Link.LinkMode - COLO
Exit Sub
StartUp:
If Err = DDE_NO_APP
t% = Shell( AppName)
Resume
Else
MsgB ox "Unknown error .·
Stop
End I f
End Sub

Sorne applications provide a topic called System that you can use to request information
about that application, such as what other tapies the application supports. Microsoft Excel
and Microsoft Word for Windows both support a System tapie ; for other applications,
consult the documentation for that application. If you are creating a sophisticated Visual
Basic application, you may want to provide a System tapie by including a form with its
LinkTopic property set to System and controls for various system items.

Microsoft Visual Basic Programmer's Guide


370 Part 4 Advan ced App lications

For more info rmation on the Shell functi on, see the Language Reference, or:

Search Help for:


ID Shell

Poking Data to Other Applications


Although the fl ow of data in a DDE conversation is usuall y from the server application to
the client application, the client can also send data to the server. As mentioned earlier in thi s
chapter, thi s is called poking data, and it is done with the LinkPoke method. LinkPoke
sends the co nte nts of the con trol to. the server applicati on. For example, thi s procedure
establishes a client link with a cell on a Microsoft Excel worksheet and changes it:
Sub Updatelt (Li nk As Control. filename As String, ne wV al As Str in g)
Const NONE = 0 . COLO= 2
' Link is assumed to be a text box control.
Li nk . LinkMode = NO NE
Lin k.LinkTopic = " Excel.l" + file name
Link.Linkltem = " RlCl"
Link.LinkMode = COLO
Link.Text = new Val
Li nk.LinkPoke
Lin k.LinkMode = NONE
End Sub

W hen used with a pictu re box control, the LinkPoke meth od sends the contents of the
Picture property (ra ther th an the Image property).

Requesting Data from Other Applications


W hen a control has initi ated a hot link, the server applicati on automati cally upd ates it
w henever the data de fin ed by the lin k changes. However, when a control has initiated a
warm link, th e server does not automatically update it. You mu st explicitly ask th e serve r to
update the contro l by exec uting the LinkRequest method on th e control:
Sub Pictur el _Click ()
Const NONE = 0 , COLO= 2
If Picturel.LinkMode - NONE Then
Picturel.LinkTopic = " Excel lc:\chartl.x l c"
Picturel.Linkltem = "Chart "
Pi ctu rel. Li nk Mode = COLO
Picturel.LinkRequest
Else
Picturel.LinkRequest
End I f
End Sub

oti ce that whcn you firs t establi sh a warm lin k, no da ta is immedi ately transferred. Yo u
must perform an exp li cit LinkRequest me th od to ge t any data in a warm link.

Mic rosoft Visual Basic Programmer's Guide


Chapter 22 Communicati ng with Other App lications 371

Sending Commands to Other Applications


You also can send commands to any application that supports DDE. Once you have
established a client link with another application, you can use the LinkExecute method on
the control that is maintaining the link.
For example you can send macro commands to Microsoft Excel. This code uses the
LinkExecute method on a control named Link to command Microsoft Excel to close the
worksheet named SHEETl.XLS:
Link .LinkExecute "[FILE .CLOSE()]"

Every appl ication accepts different command strings, so you should consult the
documentation for the application to see what commands it will accept. Microsoft Excel, for
instance, enab les yo u to send a series of macro commands with a si ngle LinkExecute
statement by enclosing each command in square brackets. For example, this code commands
Excel to save the current file and then quit:
Link .LinkExecute "[ SA VE () J[QUIT()]"

Notifying Other Applications When Data Has Changed


When a form in your application is acting as the server in a DDE conversation, Visual Basic
handles most of the details for you. If a client application initiates a conversation with a text
box control on the form, for example, Visual Basic automatically updates the client (in the
case of a hot link ) or notifies the client (in the case of a warm link) whenever the Text
property of th e text box changes.
However, Visual Basic does not do this with a picture box. Because the contents of a picture
box can be so large, and because it often takes many graphics methods to complete a change
to a picture , Visual Basic might waste time and resources updating all DDE clients every
time a pixel in the picture changes. Instead, with Visual Basic you explicitly update any
DDE clients by exec uting the LinkSend method on a picture box. This code draws random
lines on a picture box and sends the contents of the Picture property to its DDE clients (if
any) when it 's done:
Sub Pictur el _ Paint ()
Const MaxP oints = 100
Static Points(MaxPoints, 1) As Si ngle , Count As Integer
If Count <= MaxPoints Then
Point s(Coun t, 0) = Int(Rnd( l) * Picturel.Width)
Points(Count, 1) = Int(Rnd(l) * Picturel.Height)
Count = Count + 1
End I f
Picturel.P Set(Po ints(0, 0), Points(0,l))
For i% - 1 to Count - 1
Pictur el.Fo reColor = OBColor(i% Mod 16 )
Pictur el.Line - (Points(i%, 0), Points(i%, 1))
Next i %
Picturel. LinkSe nd
End Sub

Microsoft Visual Basic Programmer's Guide


372 Part 4 Advanced Applications

DDE in Other Microsoft Applications


Microsoft Excel and Microsoft Word fo r Windows both support DDE, and provide
statements in their macro languages that enabl e users to write macros that perfo rm DD E. lf
yo u have written macros in one of these Microsoft applications, you may find th e Table 22. l
he lpful. lt compares the DDE statements and functi o ns in the Microsoft Excel and Mi c rosoft
Word macro languages with the equivalent DDE properti es and methods in Vi sual Basic.
Table 22.1 DDE Statements in Microsoft Excel, Word, and Visual Basic
Microsoft Excel Microsoft Word Microsoft Visual Basic
INITIATE DDEinitiate LinkMode = Hot
or
LinkMode = Cold
REQUEST DDERequesL LinkRequest method
POKE DDEPoke LinkPoke meLhod
EXECUTE DDEExec ute LinkExecute me th od
TERMINATE DDETermi nate LinkMode = None

For more information on Link methods, see the Language Reference, or:

m Search Help for:


link

Handling Errors
As with other ac ti vities, errors can sometimes occur whe n a Vi sual Basic application is
pe tiorming DDE. The kinds of errors that occur ca n be divided into two groups :
• Errors that occur in statements , function s, or express io ns w ithin executing code in the
same way that run -time errors occur in any exec utin g code .
• Errors that occ ur when no code is being executed.

Errors of th e first kind are no differe nt th an any other run -tim e errors, and can be handl ed
with standard erro r-handling statements and function s prov ided in Visual Basic. For more
inforrnation on handling these kinds of errors, see Cha pte r 19, " Handlin g Run -Time Errors."
rora li st of ali trappable run-time errors, in c ludin g the DDE errors, see the Language
Refe rence , or:

m Search Help for:


error

Microsoft Visual Basic Programmer's Guide


Chapter 22 Commun icating with Other Applications 373

The second group of errors may seem somewhat unusual. How can an error occur if no code
is executing? To understand this, remember that Visual Basic is always performing a variety
of operations, even when none of your Visual Basic code is executing. One thing Visual
Basic does is update hot links whenever data changes. Many errors can occur at this point;
for example, the data may be in the wrong format, or it may be so large that copying it
causes Visual Basic or the operating environment to run out of memory . Visual Basic deals
with this by generating a LinkError event. You can write an event procedure to handle this
event like any other event, as explained in the next section.

Errors When a Visual Basic Application Is the Client


lf a Visual Basic application is engaged as a client in a DDE conversation , and an error
occurs when no Visual Basic code is executing, the LinkError event occurs. In Visual Basic
applications, the client in a DDE conversations is always a control, so in thi s case the
LinkError even t is a control even t. As you might expect, th e LinkError eve nt occurs at the
control involved in the conversation that caused the error.
To handle the LinkError event, you write an event procedure. The event procedure takes one
integer argument th at indicates the error that occurre·d. These DDE error numbers are
completely different from the run-time error numbers, but yo u use them in the same way to
distinguish between various errors. For a list of trappable errors, see the LinkEvent topic in
the Language Reference, or:

m Search Help for:


LinkError

For example, suppose you have a text box called CurrentPrice that is engaged as the client of
a DDE conversation. To handle errors that might occur durin g the DDE conversation, write
an event procedure like this:
Sub CurrentPrice_ LinkError (ErrNum as Integer)
Select Case ErrNum
Case OUT_OF_MEMORY
Msg$ - "Not enough memory to perform DDE . "
Case WRONG_FORMAT
Msg$ = "DDE data is not in the ri ght format. "
Case Else
' Handl e other er ror s.
End Se lect
MsgBox Msg$
End Sub

Of course, if the control is an element in a control array, there will be a second argument for
the array index .

Note The constants for various kinds of errors (for example, WRONG_FORMAT) are
defined in the CONSTANT.TXT file . If you merge this file into the global module, you can
use th ese constants in your code.

Microsoft Visual Basic Programmer's Guide


374 Part 4 Advanc ed Appl icatio ns

Errors When a Visual Basic Application Is the Server


lf a Visual Basic application is engaged as a server in a DDE conversation, andan error
occurs when no Visual Basic code is executing, the LinkError event occurs. ln Visual Basic
applications the server in a DDE conversation is always a forro , so in thi s case the LinkError
event is a forro event.
The event procedure for a server error is exactly the same as the event procedure for a client
error, except it is a forro event procedure:
Sub Form_ Li nkError (ErrNum as Integer)
Se lect Case ErrNum
Case OUT_OF_MEMORY
Msg$ = "N ot enou gh memory to perform DDE."
Case WRONG_ FORMAT
Msg$ = "DDE data is not in the right format."
Case Else
' Handle other errors .
End Select
MsgBox Msg$
End Sub

Catching and Avoiding Errors


Although you tend to think of your Visual Basic application as a completely separare thin g
from ali other running applications , remember that ali appl ications are running on the same
comp uter. In order to run simultaneously, they must share the computer. When yo ur Visual
Basic application is wai ting for an event to occur, it automati call y shares the computer with
other running applications .
However, when one of your procedures is running, Vis ual Basic does not share with oth er
applicatio ns. This can ca use problems if your procedures do many DDE operations wi th
another app lication. Since that other appli cat ion does not get a chance to run while your
code is exec uting, it cannot respond to DDE operations. This in tum causes a run -time (time -
out) error in your code. To avoid thi s, yo u can cal! the DoEvents function :
Link.LinkMode = NONE
Link.LinkTopic = "E xcel ISheetl"
Link.Linkltem = "RlCl"
ChartPic(i%).LinkMode = HOT
For i% = 1 To MAXPICTUR ES
Link.Linkltem = "RlCl" + LTrim$( Str $(i%))
Link,Text = Str$(i%)
Link.LinkPoke
Dummy %= DoEvents()
Next i%

Micros oft Visual Basic Programm er's Guide


Chapter 22 Communicating with 0ther Applications 375

Calling the DoEvents function causes Visual Basic to "yield" briefly and allow other
application s to execute. In the example above, calling DoEvents after performing th e
LinkPoke method enables Microsoft Excel to handle its side of the DDE conversation.
Sorne applications have to do more work to handle DDE than others; you may find that one
call to DoEvents is not enough, and that you must call DoEvents several times in a short
loop.
If you get a lot of run-time errors indicating that the other applications are busy or not
handling DDE properly, try placing a call to DoEvents in your error-handling code:
On Error Goto ErrHandler
' DDE code her e.
ErrHandler:
If Err = DDE_ ERROR Then
dummy%= DoE vents()
Resume
Else
Error Err
End I f

For more information on DoEvents, see Chapter 18, "Interacting with the Environment"; th e
Language Refe rence; or:

m Search Help for:


DoEvents

Sending Keystrokes to Other Applications


Sorne applications do not support DDE. Nevertheless, because all applications run in th e
same operatin g environment, sorne communication is always possible. The easiest way to
comm uni cate with app lications that do not support DDE is by sending keystrokes .

Note You can send keystrokes to any application running in the operating environment,
whether it supports DDE or not. However, you cannot send keystrokes to a DOS virtual
machine (a DOS sess ion running in a window).

When yo u se nd keystrokes to another application, it appears to the other application th at th e


user is typ ing at the keyboard. The application cannot distin gui sh between keystrokes se nt
from your Visual Basic application and keystrokes typed by the user. Thus you can make th e
other app li ca ti on perform any operation th at the user, using keystrokes, can make it perform .
For example, thi s statement sends the keys "ABC" as if they were typed at the keyboard :
SendKeys "AB C"

The key strokes don ' t actuall y get sent until yo ur Visual Basic application is
" idl e"dvbpga paw hen none of yo ur Visual Basic code is exec utin g or when the DoEvents
fun ction is called .

Microsoft Visual Basic Programmer's Guide


376 Part 4 Advanced Applic ations

But where do the keystrokes go? They go to the acti ve applicati o n (the app lication that has
the focus) . However, if the currentl y active application is not the o ne to which you want to
send keystrokes, then you ' 11 need to know how to activate other applications.

Activating the Other Application


Keystrokes that you send can only go to one place: the acti ve applicati on. If you do not
ac tivate another application, your Visual Basic application wi ll send key strokes to itself.
While thi s might be handy for testing your application , it is generall y not very useful. To
se nd keystrokes to another application, you have to actívate that applicati o n with
AppActivate statement. For exarnple, if the Windows Terminal applicati on was running,
thi s statement would actí vate it:
AppActivate "T erminal "

1f the application is not already running, you must start it w ith the Shell function (described
earlier) befare you can actívate it and send keystrokes to it.
For more information on the AppActivate statement, see the Language Reference, or:

m Search Help for:


AppActivate

Specifying Special Characters


You may want to send characters that you cannot simpl y type into a strin g, such as ENTER
an d TAB. To send these characters, you send the name of the key s urrounded by brace
c haracters ( { }). For example, to send the keystrokes for TAB, F I , and ENTER , use thi s
stateme nt:
SendKeys " {T AB} (Fl} (enter}"

T he names of the keys are not case-sensitive, so {enter}, {En ter}, and {ENTER} a li mean
the same thing.
For a complete list of the special key names, see the tapie for the SendKeys stateme nt in the
Language Reference, or:

m Search Help for:


SendKeys

Microsoft Visual Basic Programmer's Guide


Extending Visual Basic

You have reached the last chapter of this manual, but not the end of what Visual Basic can
do. One of the most distinctive features of Visual Basic is its open-endedness. Visual Basic
was designed to provide you with all the features you need to create many kinds of
applications. But at sorne point you may want to do something that seems to be beyond its
capabilities. When this happens, you can extend the capabilities of Visual Basic itself.
There are two fu ndamental techniques for extending the capabilities of Visual Basic:
• Loading a custom control fil e
• Calling a routine in the operating environment or in third-party dynamic-link
libraries (DLLs)

Custom control files provide new types of controls that become part of the development
environment and supply new capabilities to your applications. When you load a custom
control file , Visual Basic adds the custom control to the Toolbox. You then use custom
controls just like any other type of control. Custom control files are difficult to build, but
they are easy to use.
You also can make direct calls to routines in the operating environment DLLs. DLLs expand
the capabilities of the language beyond the keywords supported in Visual Basic. The
operating environment is actually made up of severa! DLLs that provide a rich set of routines
(Visual Basic itself works by calling these routines). You also can call routines in other
DLLs that you have in your sys tem. By calling these routines, you can accompli sh
speciali zed tasks that are otherwise difficult or impossible to perform with Visual Basic
alone.
The main sections in this chapter are:
• Loading Custom Controls
• Declaring and Calling DLL Routines
• Special Considerations When Declaring DLL Routines
• Calling DLL Routines with Specific Data Types
• More Information About Dynamic-Link Libraries
378 Part 4 Adv anced Appl ic ation s

Loading Custom Controls


A custom control fi le co ntain s all the in for mati on th at Vi sual Bas ic need s to provide one or
mo re new types of con tro ls. T he fil es ca n be created and di stributed by third-party
deve lopers, and you can write them yourself (see note below).

To load a custom control file:


1 Fro m the Fil e me nu , choose Add File .
2 E nter th e name o í the fi le.
Visual Basic di spl ays the Add Fil e dialog box, with three proposed fil e exte nsion s -
*.FRM . *. BAS , and *. VBX. B y co nve nti on, custo m control fil es have a .VBX ex tension .
Type or se lect the name of the custom control file you want to open.

As soo n as you load th e fil e, two thin gs happen:


• T he custom control fil e appears in the Project wi ndow.
• Ali the co ntrols provid ed by this fi le are added to the Toolbox, whi ch grows to
acco mm od ate th e new controls.

Yo u now can use th e new co ntro ls just as if they were standard controls. You ca n add them
to any of the form s in yo ur proj ec t.
Each cus tom co ntrol has its ow n se t of propert ies and events, whi ch you can see by using the
Prope rti es bar and Code w ind ow . Certain properti es - such as Ctl Name-sho uld be present
in e very cont ro l, but custom controls ca n have new properti es and eve nts beyond the scope
of standard co ntro ls. Consul t the documen tation tha t accompani es the custo m co nt ro l fil e for
inf"orma tio n o n how Lo use th ese prope rt ies and eve nts.

Note You ca n use custom controls with Visua l Bas ic, but you cann ot use Vi sual B as ic to
create c ustom co ntro ls. If you wa nt to creare custom control fil es yourself, yo u need the
Vi sual Basic Co ntro l Develop ment Kit, a se t of tools and documentati on for writin g custom
co ntro ls (ava il able fro m M icrosoft). l n add itio n. you need a software development product
that all ows yo u to create D LLs, such as M icrosoft C and the Mi crosoft Wind ows Soft wa re
Deve lopment Kit (SDK ). Wrilin g custom co ntro ls requires greater technical kn o wl edge than
what's req ui red to progra m in V isua l Basic. H owever, if you create c ustom co nt roJs, you ca n
d istribute th em to any V isua l Basic user.

vlic rosoft Visual Basic Programmer's Guide


Chapter 23 Extending Vi sua l Ba sic 379

Declaring and Calling DLL Routines


As mentioned earlier, the operating environment is made up of severa! DLLs that contain
routines you can call. You also can call routines in other DLLs you may have in your
system. Unless otherwise noted, all discuss ion in thi s chapter about making a call to a DLL
routine applies equall y to the operating environment DLLs and other DLLs.
There are two basic steps in using a DLL routine:
1. Tell Visual Basic about the routine by using a Declare state me nt.
2. Make the actual call.

You declare a DLL routine only once . You then can call it any number of times.

Declaring a DLL Routine


To declare a DLL ro utine, place a Declare statement in the global module, or in the
Declarations section of a form or module. If the routine does not return a value, declare it as
a Sub procedure. For example:
Declare Sub InvertRect Lib " User " (By Val hD C%, aRect As Recta ngle )

If the routine does return a value, declare itas a Function procedure. For example:
Declare Function IsZoomed Lib "U ser " (By Va l hWnd %) As Integer

Notice the Lib and ByVal keyword s in the Declare statement. It also ca n co ntain an
opti onal Alias keyword . The use of these keywords is explained in the sec ti on "Special
Considerati ons When Declaring DLL Routines" later in thi s chap ter.
For the complete syntax of th e Declare statement, see th e Languag e Refe rence , or:

Search Help for:


Decl are

Calling a DLL Routine


Once a routine is declared, you then can call it justas yo u would a Vis ual Basic statement or
function . For example:
Sub Form_ Resize ()
If IsZoomed(hWnd) Then
MsgBox "Th e form i s maximi zed. "
End I f
End Sub

Microsoft Visual Basic Programmer's Guide


380 Part 4 Advan ce d App lications

lmportant Visual Bas ic can' t veri fy you are passi ng correct values to a DLL routine. If you pass
incorrec t va lues, the ro utin e may fa il , whi ch may cause yo ur Visual Basic application to
crash. This doesn ' t cause perm anent harm , but yo u' ll have to reload and start your
application. Take care when ex perimentin g with DLL ro utin es and save your work often.

Special Considerations When Declaring DLL Routines


As yo u have probabl y realized, the declarations fo r DLL routines can get fairly complex.
But if you want to call a ro utine in an operating e nvironment DLL, you don ' t have to fi gure
o ut how to declare it. The Visual Bas ic package co ntains a fil e that incl udes the decl arations
for all the useful routin es in the operating environm ent DLLs. You can copy the routines yo u
want from thi s fil e and paste them into the global modul e, and then simply call the routines
fro m yo ur app li cation. Howeve r, yo u should first read the sec ti on "Ca] ling DLL Ro uti nes
w ith Spec ific Data Ty pes'· later in thi s chapter.

Note Visual Basic does not incl ude the doc ument ati on fo r the routines in the operating
e nvironment. The ro utin es are documented in the SDK, and in the Microsoft Windows
Programmer 's Reference published by M icrosoft Press.

If you are attemptin g to call a ro utine in a DLL that is not part of the operating environme nt,
you mu st determine the proper declaration fo r it. T he rest of thi s sec ti on explains the sy ntax
of the Declare state ment in deta il so that you ca n create the correc t declaration fo r the
routine.

Specifying the Library


T he Lib libname c lause in the Declare statement te ll s Visual B asic where to fi nd the
dynami c-lin k lib rary. For the o peratin g enviro nme nt DLLs, thi s is either "User," "GDI ,"
" Kernel," or one of the device driver DLLs such as "Soun d." For other DLLs, the libname is
a fil e specificati on that can inc lu de a path . For example:
Dec l a r e Function lzC opy& Lib " c:\win\lzexpand.dll" (By Val S%, By Val 0%)

Noti ce that the libnam e is not case sensitive.

Passing Arguments by Value or by Reference


By defa ult , V isual Bas ic passes ali argum ents by reference. (Whe n pass in g by refere nce,
V is ual Basic s uppli es a 32- bi t far add ress.) However, many DLL ro utines ex pec t an
arg umen t to be passed by va lue . lf you pass an argume nt by refere nce to a ro utine that
ex pec ts an arg um en t passed by va lue, the routi ne gets bad data and fa il s to operate properly.
To pass an arg um en t by value, place the By Va l keyword in fro nt of th e arg um ent declaration
in the Declare statement. Thi s ens ures that each time you call th e ro uti ne, the arg um ent is
passed by \·al ue.

Microso ft Visual Basic Programmer 's Guide


Chapter 23 Extending Visual Basic 381

For example, the lnvertRect routine accepts its first argument by value and its second by
reference:
Declare Sub InvertRect Lib "User" (By Val hDC%. aRect As Rectangle)

Note When you're looking at DLL routine documentation that uses C language sy ntax,
remember that C passes ali arguments by value except arrays .

Flexible Argument Types


Sorne DLL routines can accept more than one type of data for the same argument. To pass
more than one type of data, declare the argument with As Any to remove type restrictions.
For example, you can declare a routine like thi s:
Declar e Function fcCreatelmage Lib "fx" (i As Any, ByVal f lag %) As Int eger

You then can call this routine with either a string ora long integer as its first argument:
re su lt s% - fxCreatelmage(imageStr$, flag Var%)
results% = fx Cre atelmage(ByVal imageVal&, flagVar%)

Note that w hen you remove type restrictions, Visual Basic assumes the argument is passed
by reference. Use ByVal in the actual call to the routine (as shown in the second example
above) to pass arguments by value .

Nonstandard Names
Occasionally, a DLL routine has a name that is nota legal identifier: It mi ght have an invalid
character (such as a hyphen) , or the name might be the same as a Visual Basic identifi er
(such as Loop) . When thi s is the case, use the Alias keyword .
For example, there are routines in the operating environment DLLs that begin with an
underscore character. While you can use an underscore in a Visual Basic identifier, you
cannot begin an identifi er with an underscore. To use one of these routines, you mu st declare
the routine with an ali as:
De c lar e Function Lüpen % Lib " ker nel" Alias "_ lopen" (ByVal fn$, ByVal f%)

In this example, LOpen% becomes the name of the routine as it is referred to in your Visual
Basic procedures. The name _ l open is the name recognized in the DLL.
You can use the Alias clause whenever it' s convenient. For example, thi s Declare statement
substitutes a shorter nam e (SetBlink) for the ful] name (SetCaretBlinkTime) :
Declare Sub SetB link Lib "User" Alia s " SetCaretBlinkTime" (By Val count%)

Microsoft Visual Basic Programmer's Guide


382 Part 4 Advanced Appli cation s

Calling DLL Routines with Specific Data Types


Visual Basic incorporates a rich assortment of data types, including m any - such as
vari able- length strings, Currency, and properties- that are not supported by the routines in
most dynamic-link libraries. Therefore, take care when using Vi sual Basic variables with
DLL routines .

Strings
The routines in most DLLs expect standard C strings (sometimes called ASCIIZ strings),
which endina null character (ANSI zero) , If a DLL routine expects a C string asan
argu ment, declare the argumentas a string with the By Val keyword. When used with a
strin g arg um ent, ByVal tell s Visual Basic to pass the string as a C string ending with a null
character. For exa mpl e, the RegisterClipboardForma t rout ine accepts a string th at names a
new C lipboard for mat:
De cl are Function RegisterC lipboardF ormat% Lib "U se r" (By Val FormatName$)

Because th e string argument for thi s routine is declared with ByVal, Vi sual Bas ic
auto maticall y converts a variable-length strin g passed to this routine into a standard C string:
FormatNumbe r % = Reg i sterCl ipboardForm at%( " RTF " )

Sorne DLLs m ay be written specifically to work with Visual Basic . A DLL can be written to
use standard Visual Basic strings, usin g routines that Vi sual Basic suppli es far this purpose
(th ese rout ines are doc umented in the C ustom Con trol Development Kit). If a DLL routine
eXpects a Visual Basic s trin g asan arg umen t, you do not need to declare the arg um ent with
the By Val keyword . In additi on, sorne of th e DLL routin es written far Vi sual Bas ic rnay act
as run ct ions th at return st1ings. A DLL routine cannot actas a function that return s strin gs
unl ess it was writte n specificall y far use with Visua l Basic. A DLL written specificaJly far
Vi sual Bas ic probably suppli es a file co ntainin g the co rrect Visual Basic declaration s far th e
rout in es in the DLL. Consult the doc umentation far the DLL fa r detail s.

DLL Routines that Modify Strings


Because strings are passed to DLL routines by reference, a DLL routin e can m od ify a Vi sual
Bas ic string va ri ab le it receives asan argum e nt. However, be careful when callin g a DLL
routi ne that mod ifies a strin g. A DLL cann ot in crease th e length of a Visual Bas ic strin g and
si mply writes beyond the end of the string if it is not lo ng e nough. This corrupts othe r areas
of memory . You can avo id this problem by makin g the string arg ument large eno ug h th at the
DLL routine ca n never write past the end of it.
For exa mpl e, the GetWindowsDirectory routin e return s th e path far the Windows direc tory
in it s íirst arg um e nt :
Declare Function GetWindowsDirectory% Lib " Kernel " (By Val f$. ByVal flen%)

Microsoh Visual Basic Programm er's Guide


Chapter 23 Extending Visual Basic 383

A safe way to call this routine is by first making the returned argument at least 255
characters long by filling it with characters - in this case null (ANSI O) characters:
Path$ = Stri ng$(255, 0)
worked % = GetWindowsDirectory(Path$, Len(Path$) )

Another solution is to define the string as fixed length :


Dim Path As String * 255
worked % = GetWindowsDirectory(Path$, Len(Path$))

When calling a DLL routine, Visual Basic always converts fixed-length string arguments to
variable-length strings. So both of these processes amount to the same thing: creating a
variable-length string long enough to contain the largest possible string that the routine
mi ght return.

Note The operating environment DLL routines generally do not retum strings longer than
255 characters While this is true of many other libraries, always consult the documentation
for the routine in question.

Visual Basic strings can be used when the DLL routine calls for a memory buffer. Use one
of the processes outlined above to ensure that the string is large enough to accept whatever
data the routine supplies.

Arrays
You can pass individual elements of an array the same way you pass any variable of th e
same type as the base type of the array. For example, you can use the RegisterCl ipboard-
Format routine declared earlier to register a series of fom1ats stored in an arra y:
For i% = 0 to UBound(ClipboardFormats$)
FormatNumber(i%) = RegisterClipboardFormat(ClipboardFormat s $(i%))
Next i%

You cannot pass an entire array to a DLL routine as you would pass an entire array to a
Visual Basic procedure. Remember that you can pass an en tire arra y to a procedure that
accepts an array asan argument by passing the array with empty parentheses. You ca nnot do
this with DLL routines. Instead, you can pass an entire numeric array by passing the first
element of the array by reference. This works because numeric array data is always laid out
seq ue ntially in memory . A DLL routine given the first element has access to ali th e
ele ments.
This is not true of string anays , however. If a DLL routine attempts to access me mory
beyond the end of the first element in a string array, it may co rrupt memory or cause an
error. If a DLL routine expects a buffer passed by reference as an argument, yo u shou ld
suppl y either the first element in a numeric array ora strin g. In eith er case, the array or the
string sho uld be at least as large as the routine expects so that it does not write past the end
and corrupt memory.

Microsoft Visual Basic Programmer's Guide


384 Part 4 Advanced Applications

User-Defined Types
Sorne DLL routines take user-defined types as arguments. These are referred to as
"structures" in C and "records" in Pascal. DLL documentation often uses the C terminology .
As with arrays, you can pass the individual elements in a variable of a user-defined type the
same way you would pass ordinary numeric or stri ng variables.
You can pass an en tire user-defined type as a si ngle argument if you pass it by reference.
User-defined types cannot be passed by value. Visual Basic passes the address of the first
element, and the rest of the elements of a user-defined type are packed in memory followin g
the first element. For example, severa] routines in the operating environment DLLs accept a
user-defined type with this structure, which is placed in the global module:
Type Rectangle
Left As I nteger
Top As Integer
Right As Integer
Bottom As Integer
End Type

Two of the routines that accept a rectangle are DrawFocusRect, which draws a dotted outline
around the specified rectangle, and InvertRect, which inverts the colors of the specified
rectangle. To use the routines, place these declarations in the global module:
Declare Sub DrawFocusRect Lib "U s er" ( ByVa l hDC%, aRect As Rectangle)
Declare Sub InvertRect Lib "User" (By Va l hDC% , aRect As Rectangle)

Then declare a form-level variable in the Declarations section of a form :


Dim MouseRect As Rectangle

Now you can use the following Sub procedures to cal! the two routines - one to display a
rectangle as you drag the mouse, and one to inven the rectangle when you release the mouse
button:
Sub Form_MouseDown (Button As Integ e r. Shi ft As Integer, X As Single,
• Y As Sing l e)
ScaleMode = 3
If Button And 1 Then
MouseRect.Left = X
MouseRect.Top = Y
MouseRect.Right = X
MouseRect.Bottom = Y
End I f
End Sub

M icrosoft Visual Basic Programmer's Guide


Chapter 23 Extending Vis ual Basic 385

Sub Form_MouseUp (Button As Integer, Shift As Integer. X As Single.


• Y As Single)
If Not (Button And 1) Then
MouseRect.Right = X
Mou seRect .Bottom = Y
Inv e rtRect hDC , Mou seRect
End I f
End Sub

Sub Form MouseMove (Button As Integer, Shift As Integer, X As Single.


• Y As Single)
If Button And 1 Then
DrawFocusRect hDC. MouseRect
Mou seRect . Right = X
MouseRect.Bottom = Y
DrawFocusRect hDC, MouseRect
End I f
End Sub

Notice that these routines expect the values for the rectangle to be expressed in pixels, so
you should set the ScaleMode property of the form to 3 - Pixel at design time.
Most routines that accept user-defined types do not expect the user-defined type to contain
string data. However, you ca n pass a user-defined type that includes string elements to a
DLL routine. If the string elements are fixed-leng th strings, they are packed in memory li ke
any other value. However, vari ab le-length strings are incorporated in a user-defined type as
string descriptors, a Vi sual Basic data structure which takes four bytes for each variable-
length string element. Unl ess a DLL routine is written specificall y for Visual Basic, it cann ot
use a use r-defi ned type that co ntai ns variable-length strings .

Null Pointers
Sorne DLL routi nes occasionally expect to receive a null pointer as an argument. If you need
to pass a null pointer to a routine, declare the argument with As Any (as described earlier in
the section "Flexible Argument Types") and pass the expression By Val 0& .
For exarnpl e, the FindWindow routine accepts two string arguments, so you would expect to
dec lare it like thi s:
Declare Function FindWindow% Lib "U se r" (By Val Cl ass$, ByVal Captio n$ )

However, Fi ndWindow also accepts a null pointer for either or both of its arguments. If you
declare it in this way you cann ot pass null pointers to it. Passing a zero-length string (" ")
does not work ; thi s passes a pointer to null string, nota null pointer.
The so lution is to declare the routine like thi s:
Declare Function FindWindow% Lib "U ser " (C l ass As Any, Cap tion As Any)

Microsoft Visual Basic Programmer's Guide


386 Part 4 Ad vanced Appli cations

Now you ca n call the routine and pass it two strings as you normally would. But you also
can pass a null pointer as one of the arguments if you wish :
hW ndExcel% - Fin dWin dow%(ByVa l 0&, "Mi c ro s oft Exce l " )

Noti ce the ampersand character after the zero. This informs Visual Basic that you are
passing a Long integer (32-bit) zero. This ensures that a null pointer of the right size is
passed : Pointers in Visual Basic are always far (32-bit) pointers.
You can use thi s technique to pass a null pointer to any routine that accepts an argum ent by
reference.

Handles
The operati ng e nvironment DLL routines make extensive use of handles: handl es to
Window~ (hW nd), ha ndl es to Device Contex ts (hDC), and so on . (A handle is a uniqu e
integer value defined by the operating environment and used to refer to objects such as
form s or control s.) When a routine takes a handle as an argument, always declare it as a
ByVal Integer. DLL functions that retum a handle can be declared as Integer function s.
Handl es are ID numbers; they are not pointers and they are not numeric values . You should
ne ver pe1f orm mathe matical operations on them.
The hWnd property of forms and the hDC property offorms and picture box control s suppl y
valid handles that you can pass to DLL routines. Like any other property passed to a DLL
routine, they can only be passed by value.

Properties
Properti es must be passed by value . If the corresponding argum ent is declared with By Val.
the n yo u ca n pass the property direc tly. For exa mple, you can determin e th e dimen sions of
the screen or printer in pi xels with thi s routine:
Declare Func tion GetDe vi ceCaps% Lib " User " ( ByVal hD C%, ByVal nlndex%)

You can pass the hDC property of a form or the Printer object to thi s routine to obtain th e
resolutio n of the scree n or the currently selected printer. For example:
Sub Form_Click ()
Co nst H - 8 , V - 10
Print "Sc reen resol ut i on"
Pri nt GetDevi ceCaps%( hD C. H) ; "x" ; GetDe vi ceCaps%( hDC. V)
Print " Printer resolut i on "
Print GetDeviceCaps%(Pr in ter. hD C. H) ;" x" ;Get DeviceCaps%(P rint er. hDC . V)
End Sub

Microsoft Visual Ba sic Programmer's Guide


Chapter 23 Extending Visual Basic 387

To pass a property by reference you must use an intermediate variable. All strings are passed
by reference; therefore, to pass a string property to a DLL routine, you must first assign the
property to a string variable and then pass the variable to the routine. Far example, suppose
you want to use the GetWindowsDirectory routine described earlier to set the Path property
of a file list box control. You cannot do this:
work ed% = GetWindowsDirectory(Filel.Path, Len(Filel.Pathl

Instead, use the following code to pass a property to this routine:


Temp$ = String$(255, 0 )
wo rked% = GetWindowsDirectory(Temp$, Len(Temp$))
Filel.Path = Temp$

Use thi s technique with numeric properties as well if you want to pass them to DLL routines
that accept an argument by reference.

Forms and Controls


You cannot pass a form or control to a DLL routine unless the DLL has been written
specifically far Visual Basic. Forms and co ntrol s are actually complex data structures, and
DLL routines that don ' t take thi s into account - such as the routines in the operating
environment DLLs - cannot make use of forms or controls passed to them. Likewise, you
cannot pass any of the special objects (Screen, Clipboard, Printer, or Debug) to a DLL
routine .

Microsoft Visual Basic Programm er's Guide


Appendix A Adapting Basic Code 391

Appendix B lcon Library 399

Appendix C Glossary 411


Adapting Basic Code

Code written in other versions of Basic can be imponed into a Visual Basic application,
although sorne modification usually is required. This appendix explains how to import Basic
files and lists guideli nes for making the required modifications.
Visual Basic keywords are shown in mixed case (for example, Dim) . Keywords in other
versions of Basic are shown in uppercase (for example, DIM) . However, you don't need to
alter the case of keywords when adapting Basic code. Visual Basic accepts keywords in any
case and translates them to their mixed-case form au tomatically.
The mat erial that follows uses the term "BAS ICA' ' to refcr to both BASICA and GW -
BASIC. Microsoft QuickBasic and the Microsoft Basic Professional Development System
are both referred to as "procedural Basic."

Microsoft Visual Basic Programmer's Guide


392 Part 5 Appendix es

lmporting Basic Files


You can import an ASCII file containing Basic code by choosing the Load Text comma nd
from the Code menu . As Visual Basic imports the Basic code, it places the modul e- leve!
declarations in the Declarations section of the current form or module.
When you choose the Load Text command, Vis ual Basic displays a dialog box that presents
severa! options. C hoose Replace only if you want to lose ali existin g code in the curre nt
form or modu le . Choose Merge to combine the ASCII file with any ex isting code.
For more information on the Load Text command:

Search Help for:


load text

Program Structure
Form code and modules in Visual Basic are rough ly equivalent to modules in procedural
Basic. Forrn code is different, however, in that proced ure s in a formare not visible to the
rest of the appli cation.
In Visual Basic, ali exec utable code mu st occur inside a Sub or Function procedure . (The
term "execu tab le code" refers to ali statements that perform sorne action at run time.) In a
typical application , most statements are executab le.
onexecutable statements include variable declarat ions, Deftype stateme nts, and co nstant
and Type defin iti ons. These state ments can be placed ins ide Sub and Function procedures,
in the Decl ara tion s sec tion of the form or module. and in the g loba l module .

Program Structure and BASICA


BAS ICA programs do not have procedures, so one of the principal tasks in adap tin g
BASJCA code is to place statements in Sub and Function procedures. Jf the program is very
simp le- for example, it carries out a single activity , such as a calculation-aJl the
sta tements can be placed in a si ngle event procedure.

Program Structure and Procedural Basic


Sub and Function procedures from a procedural Basic program can often be preserved
wit hout change, particu larly the ones that don't involve direct input or output. However, you
must modify ali module-leve] code (except for dec larati ons and defini ti o ns) by plac in g it in
o ne o r more procedures.
Module-leve! code th at performs initialization shou ld be placed in a Form_ Load or Main
procedure. If yo u designate a startup form for your appl icat ion , Vi sual Basic starts the
app li cation by loading th at form and then invokin g its Form_Load proced ure. If yo u set Sub
Main as th e startup rather than a fo rm , Visua l Bas ic starts by invok in g th e Main procedure .

Microsoft Visual Basic Progra mmer's Guide


Appendix A Adapting Basic Code 393

If you have code th at you want to execu te continu all y (ge nerall y unnecessary with Visual
Bas ic's event-driven stru cture), you can pl ace it in a Main procedure and use an indefinite
loop. lf yo u use such a loop and want th e appli cati on to be able to res pond to events, the
loop should start with the statement Wh i le DoEvents (). For more information on the
DoEvents statement, see Chapter I 8, "Interacting wi th th e Environment," or:

m Search Help for:


DoEvents

GoSub, DEF FN, and Line Labels


Visual Basic supports GoSub routines but not DEF F functions. A GoSub routine, ancl ali
the statements that cal! it, must occur wit hin a single procedure . Visual Basic supports line
labe ls (both numeric and named), which you ca n use as the targe t of a GoSub or GoTo
statement. However, ali references to a linc !abe! rnu st be local to the proceclure.
For example, the following code is valid as long as it is ali within the same procedure:
GoSub InitArray

InitArray:
Far I = 1 To 100
Arrayl(I) - I
Next I
Return

GoSub ro utines can be rew ritten as Sub proccdurc~. and GoTo statements are on ly
occasionall y needed if yo u use Visual Basic ·~ control structures.
Rewrite ali DEF FN functions as Function procedures. Refer to Chapter 9, "Language
Element ," for more inform at ion abo ut th e syntax ora Function procedure.

Calls Between Modules and the Declare Statement


In Visual Basic, the Declare statement is in valid exce pt for dy nam ic-link library (D LL)
routines and Function procedures wi th no arguments. Using Declare in the latter case is
useful if yo ur code makes calls to these function s without use of parentheses. (For more
information on call s to Function proced ures, sec the sec ti on "Language Mechanics" later in
thi s ap pendi x.)
Remove ali yo ur Declare statements, except for any th at fall into one of th e two cases
mentioned above .

Microsoft Visual Basic Programmer's Guide


394 Part 5 Append ixes

Scope of Variables
Scope determines how much of the application recognizes a variable. For your adapted code
to run without errors, you should attempt to preserve the scope of each variable. Where you
cannot preserve scope exactly, you may need to avoid conflicts by chan ging the names of
sorne variables.

Scope and BASICA


In BASICA, all vari ables are shared by the entire program; in Vi sual Basic, variables are
local by defau lt. After importin g your BASICA code, yo u can leave all variables local (the
default) and th en declare variables to be form- level, module-leve!, or global only where
there is a genuine need to share information between procedures .
Alternatively , yo u can Ii st ali variables used and then declare th e rn at the form or modul e
leve!. This simulates the BASICA behavi or of making ali vari ables g lobal.

Scope and Procedural Basic


Local variables in Basic programs translate withou t change in to Visual Basic, unless they
match a control , property, or the form name- in which case yo u mu st change the names.
T he following table shows how to translate Basic declarations into eq ui valent Visual Basic
declarations. COMMON SHARED statements in a Basic program should be replaced by
Global declarations in the global modules. DIM SHARED statemen ts at th e module leve!
are supported in Vis ual Basic , but they are interpreted as Dim statements. However, you
should use Dim rather than Dim Shared Note that in Visua l Basic, module- leve! variables
are always shared with procedures .
Procedural Basic Visual Basic
declaration Location declaration Location
DIMX Procedure DimX Procedure
DIMX Mod ul e leve! (not supported)
COMMONX Modu le leve! (not supported)
DIM SHARED X ' Module leve! DimX Forrn or modul e
declaratio ns
COMMON
SHAREDX Module leve! Global X G lobal module

Procedural Basic supports o ther variations on scope throu g h use of SHARED statern ents
wi thin procedures: Specifically , a vari able can be declared at th e module leve!, then shared
by one proced ure but not anoth er. Visual Basic does not support thi s approach to scopin g. If
you have varia bl es declared thi s way, make thern form- leve l or modu le-leve! by plac in g a
Dim stateme nt in the form or module Declarations sec tion.

Microsoft Visual Basic Programmer's Guide


Appendix A Adapting Basic Code 395

Events and Error Handling


You can write code far an event only if it is one of the events that Vi sual Basic defines far
sorne object. Of the events supported in Basic, keystroke, mouse, and timer events are
supported as Visual Bas ic events, although pen and joystick events are not. Another way of
trapping events or res ponding to special hardware devices is to make calls to the operating
environment.
The one type of event far which you do use the On keyword is errors. Visual Basic supports
error handling in roughly the same way as other versions of Basic. However, an error
handler must be local to a procedure. See Chapter 19, "Handling Run-Time Errors," far
more infarmation.

Input and Output


Visual Basic supports the Print keyword as a method. A PRINT statement, imported into a
Visual Basic procedure, appears as a use of Print with no object specified . Far example:
Print X, Y, Z

In Visual Bas ic, this statement has the same effect as it does in Basic, but the statement
prints to the current farm (that is, the fa rm to which this statement is attached) rather than
the background screen.
Alternative methods fa r displaying outpu t include:
• Printing to a picture box instead of the current form by preceding the Print method with
a reference to a picture box:
Picturel.Print " X has a value of " ; X

• Displ ay ing a string by ass igning it to the Tex t property of a text box or the Caption
property of a !abe]:
Text2 . Text - " X has a value of "+ Str$(X)

• Display ing a message by using th e MsgBox statement. The message appears in a dial og
box that is closed when the user clicks th e OK button:
MsgBox " X has a value of " + Str$(X)

Visual Bas ic supports INPUT# and LINE INPUT# statements only far working with fil es.
However, generall y you can replace INPUT statements with calls to the InputBox$
function . INKEY is not supported in Visual Basic; instead of using INKEY, design your
application to respond to KeyPress events. You also can create a text box and read input by
using the Tex t property.
The file input and output statements (far example, INPUT#, PRINT #) workjust the same
as in procedural Basic.

Microsoft Visual Basic Programmer's Guide


396 Part 5 App endixes

Language Mechanics
Certain differences in dctails of the languages can cause syntax errors. Fortunate ly , resolving
these is usually strai ghtforward :
• Variable and symbolic co nsta nt names. You cannot use a period (.) in these names. The
period has a special meanin g in property , method , and user-defined type references.
• Array s. You cannot implicitly define an array in Visual Basic. Arrays mu st be explicitly
declared with Dim or Redim .
• Line continuation . Visual Basic does not have a line-continuation character, but it has a
scro ll ab le Code window th at supports lines up to 256 characters in length .
• Name confli cts. There is no conflict if two variables in different procedures, or at
differcnt levels of scope, sharc th e sa me name. However, two vari abl es at the sa me leve!
of scope cann ot have the same name , even if they have different types: A procedure
cann ot have both X% and X$as local variabl es.
• F unction call s. A call to a Function procedure must use parentheses, even if there are no
argume nts. For exampl e:
N = Get ARandom ( )

Note th at the parentheses can be omitted if your modul e or fo rm includes a Declare


state me nt for th e Function procedure you are callin g.

Unsupported Keywords
Vi sual Bas ic does not support th e keywords li sted below :
BLOAD BSAVE CALL ABSOLUTE CA LLS
CHAIN CLEAR COLOR COM
CSRLIN CVD CVDMBF CVI
cvs CVSM BF DATA DEFFN
DEFSEG DRAW ERDEV ERDEV$
FIELD FILES FRE INKEY$
INP IOCTL IOCTL$ KEY
LOCATE LPOS LPRINT MKD$
MKI$ MKL$ MKS$ MKSMBF$
ONCOM ON KEY ONPLAY ON STRIG
ONTIMER OUT PAINT PALETTE
PCOPY PEEK PEN PLAY
PMAP POK E POS PRESERVE

Microsoft Visual Basic Programmer's Guide


Appendix A Ad apting Basic Code 397

PRESET RESTORE RUN SADD


SCREEN SETMEM SLEEP SOUND
STICK STRIG SWAP TROFF
TRON USING$ VARPTR
VA RPTR$ VARSEG VIEW
WAIT WIDTH LPRINT WINDOW

In m any cases, a keyword is not supported because Visual Basic uses a differe nt approach to
ach ieve the same result (either simplifying the process or adding fl ex ibility). For exampl e,
the LPRINT statement is not supported because Visual Basic has a spec ial Printer objec t
which handles ali output to the sys tem printer. Check the index of thi s manual or co nsult
He lp befare dec iding th at a ca pability is simpl y not supported.
In other cases, a keyword is not supported because it attempts to carry out low -leve l
operati ons th at confli ct with th e Windows or Presentation Manager environme nt.

Keywords with Specific Differences


The keywords discu ssed in thi s section are supported in Vi s ual Basic, but yo u may need to
change how yo u use them .

Declare
The Declare statem e nt is va l id only for DLL routines and for dec laration of Function
procedurcs w ith no arg umen ts. ft is req uired in the case of DLL routines.

Deftype Statements
The Defrype state men ts (s uch as Deflnt, DefSng. and so on) are valid o nl y in the
Dec laration s sec ti on of a fo rm or module, and in the global module. Deftyp e state me nts
cann ot appear at the procedure leve!. A lso, they must occur before any Declare s tate ment.

Dim and ReDim


The Dim stateme nt can appear at any leve! of scope. Within a proced ure, the Dim state me nt
mu st appear before a li exec utab le state ments. Dim creates a fixed array if yo u spec ify
dime nsio ns. For exampl e , the fo ll ow ing statement creates a fixed array:
Dim Fixle nArr(40)

To dec lare a dynamic array, use Dim with an empty li st of dimen sions and late r use ReDim
to a ll oca te space:
Dim DynArray()

You a lso ca n crca te an array j ust by usin g ReDim . No te that ReDim is an exec utab le
statem e nt and ca n o nl y appear in side a procedure .

Microsoft Visual Basic Programmer's Guide


398 Part 5 App endixes

Input$
The statement Input$ (x, channe[) causes the end-of-file (EOF) condition only when it
attempts to read from a file in which O bytes are left. In other versions of Basic, thi s
statement causes the EOF condition when fewer than x bytes are left.

On Error GoTo
In the statement On Error GoTo line, the target line must be in the same procedure as the
statement. This follows from the rule that references to labels must be local. In other
versions of Basic, the label can be at the module leve!. Visual Basic accepts ON LOCAL
ERROR GOTO statements, but changes them to On Error GoTo.

Option Base
The Option Base statement is valid only in the Declarations section of a form or module,
and in the global module. The statement must occur before any array references. (Option
Base enables you to specify the default lower bound for arrays.)

Return
The ordinary Return statement is valid. However, Return linelabel and Return linenumber
are not.

Width
Use Width # filenumber, O to indicate th at a file or device has unlimited width. In other
versions of Basic, the number 255 was used to indicate unlimited width rather than O. In the
statement Width # fi lenumber, N, if N is greater than O, then N indica tes where to wrap to th e
nex t line.
Vi sual Basic does not support the fo ll owing Basic syntaxes:
WIDTH screenwidth o/o, screenheight o/o
WIDTH device$, width o/o

,//icrosoft Visual Basic Programmer's Guide


lcon Library

Visual Basic comes wi th a collection of about 400 icons that you can use to enhance your
applications . This appendix shows printed examples of all the icons. Bear in mind that they
were designed to be used online, where they appear in full color (16 colors) .
For information on how to add icons to your Visual Basic applications, orto see exampl es o!'
the icons online:

Search Help for:


111 lean Libr ary

The icons in the Icon Library are divided into the following categories.
Graphics Category Directory Description
Arrows and Pointers Arrows Arrows, pointers
Communication Comm Networking, phones,
printers, servers
Computers Computer Computers, disk drives,
diskettes, keyboards, mice
Flags Flags International flag s
Mail Mail Mailboxes, envelopes
Miscellaneous Mise Clocks, first aid signs, locks
and keys, phases of the
moon , and so on.
Office Office Cardfiles, charts, file
cabinets, folders, graphs,
paper clips
Traffic Signs Traffic Traffic signs
Writing Writing Books, notepads, pens,
pencils

Microsoft Visual Basic Programmer's Guide


400 Part 5 Appendixes

Arrows and Pointers

r--··-...

ARW01DN ARW0lLT ARW0lRT ARW0lUP ARW02DN ARW02LT

~
ARW02RT ARW02UP ARW03DN ARW03LT ARW03RT ARW03UP

•·
ARW04DN
~
ARW04LT
¡ ¡.
ARW04RT
•· +
ARW04UP ARW05DN
+
ARW05LT

ARW05RT
t •
ARW05UP ARW06DN
.
<-
ARW06LT
~
ARW06RT
.)

V
ARW06UP

• • •- • •
ARW07D N ARW07LT ARW07RT ARW07UP ARW08DN ARW08LT

t
ARW08RT
,. ARW08UP ARW09DN ARW09LT ARW09RT
.
{J
ARWl0NE

(}
ARWl0NW
~
ARWl0SE
~'
ARWl0SW
.i~
-'-~'
,.. ~,.
__

ARWllNE
11~;·~
ARWllNW
iif
ARWllSE

Microsoft Visual Basic Programmer's Guide


Appendix B lcon Library 401

-, ~T. .,
~~

ARW11SW POINT01 POINT02 POINT03 POINT04 POINT05

l
POINT06
l
POINT07 POINT08 POINT09 POINT10 POI NT11

POINT12 POINT13 POINT14 POINT15

Communication
,,.;.,;._~ --
~;. ·•.... .-.-.'"ftJ)J
~D_.,./ ~J:f
NET01 NET03 NET04 NET05 NET06

~
cy;J
NET07 NETOS NET09A NET09B NET10A NET10B

NET11 NET12
• '-"'--
NET13 NET14 PHONE01 PHONE0 2

PHONE03 PHONE04 PHONE05



PHONE06 PHONE07 PHONE08

Mic rosoft Visua l Basic Programmer's Guide


402 Part 5 App endixes

PHONE09
·~
< <~:

PHONE10
~
PHONE11 PHONE12
~
.
PHONE13

Computers

~ 4
ii iil ~
._llll
DISK01 DISK02 DISK03 DISK04 DISK05 DISK06

aDISK07 DISK08
a
DISK09
~
DISK10

DISKl 1
.
//<:z:.....
~(~
DISK12

E]
DISK13
~
DISK14
.
A
DISK15 •
DISKS0l
~
DISKS02
~
DISKS03

~
DISKS04 DRIVE0l DRIVE02
fn
KEY0l KEY02
l!J
KEY03
'

~\
1 - ::~.
,~ r . . i:-:=:. • ~
¿~:-~~;>-~$:;::;:). :=:

~ d> t~I
KEY04 KEY05 KEY06 KEY07 KEYBRD0l KEYBRD02

~
,./~
~
~
<~~--
·-..~.- -· l~I
KEYBRD03 KEYS0l KEYS02 KEYS03 MAC01 MAC02

Micro soft Visua l Basic Programmer's Guide


Appendix B lean Library 403

MAC03 MAC04 MONITR01 MOUSE01 MOUSE02 MOUSE03

S.
MOUSE04 PC01 PC02 PC03 PC04 TRASH01

TRASH02A TRASH02B TRASH03 • o


TRASH04A TRASH04B

Flags

FLGASTRL FLGAUSTA FLGBRAZL FLGCAN FLGDEN FLGFIN

FLGFRAN FLGUK FLGGERM FLGJAPAN FLG IREL FLGITALY

FLGMEX FLGNETH

FLGNORW FLGNZ

FLGPORT FLGSPAIN

FLGSWED FLGSWITZ

FLGTURK FLGUSA01 FLGUSA02
111
FLGUSSR

Microsoft Visual Basic Programmer's Guide


4-04 Part 5 Appendixes

Mail

MAILOlA MAILOlB MAIL02A MAIL02B MAIL03 MAIL04

di\
---~)

MAIL05A MAIL05B MAIL06 MAI L07 MAIL08


w
MAIL09

MAILlO MAILll MAIL1 2 MAIL13


1
MAIL14 MAIL15

MAIL16A MAIL16B MAIL17 MA IL18

Miscellaneous
.,,,.,--... _

(;~.)
'-.......:,.,,'

CLOCKOl CLOCK02 CLOCK03 CLOCK04 FACE01 FACE02

@
FACE03 MISC01 MISC02
A
MISC03 MISC04
o
MISC05

=MISC06 MISC07 MISC08


LL
/•,

MISC09 MISC10 MISC11

Microsoft Visual Basic Programmer's Guide


.•
Appendix 8 lean Library 405

~-..)

MISC12 MISC13
~---
1,

MISC14
-~~--

MISC15
1~1
MISC16A MISC16B

••
MISC17A MISC17B
+
MISC18 MISC19
XMISC20 MISC21

,11~m11
MISC22 MISC23 MISC24 MISC25 MISC26 MISC27

MISC28 MISC29 MISC30 MISC31 MISC32 MISC33

• ~~
MISC34 MISC35 MISC36 MISC37 MISC38

,
'MISC39A

MISC39B MISC40
il
MISC41 MISC42
~-)
~-
-- ~
MISC43 MISC44

MISC44 MOONOl
e -
MOON02 MOON 03 MOON04 MOON05

Microsoft Visual Basic Programm er's Guide


406 Part 5 App endixes

MOON06 -
MOON07 MOON08 SECUROlA SECUROl B SECUR02A

*'3
SECUR02B SECUR03 SECUR04 SECUR05 SECUR06 SECUR07

~
QJ
.·····~~ ·.
... .·
·.-:···

SECUR08 TIMEROl WATCHOl WATCH02

Off ice

CLIPOl CLIP02 CLI P03 CLI P04 CLIP05 CLI P06

¡·p
/ ·•.

CLI P07 CLIP08 CRDFLEOl CRDFLE02 CRDFLE03 CRDFLE04

CRDFLE05 CRDFLE06 CRDFLE07



CRDFLE08 CRDFLE09 CRDFLElO

CRDFLEl 1 CRDFLE12 CRDFLE13 FILESOlA FILESOl B •


FILES02A

Microsoft Visua l Basic Programmer's Guide


Appendix B lean Library 407

11
FILES02B FILES03A FILES03B FILES04 FILES05A FILES05B

FILES06 FILES07 FILES08 FILES09 FILES10 FOLDER01

FOLDER02 FOLDER03 FOLDER04 FOLDER05 FOLDER06 FOLDRS01

FOLDRS02
.... ., ......
GRAPH01
"

GRAPH02 •
GRAPH03 GRAPH04 GRAPH05

·j J.lfi·
:lllBl 1111 11111
GRAPH06 GRAPH07 GRAPH08 GRAPH09 GRAPH10 GRAPH11

GRAPH12
..
--~
• ...
GRAPH13 GRAPH14

Microsoft Visual Basic Programmer's Guide


408 Part 5 App endixes

Traffic Signs

(~
,JI
TRFFC01 TRFFC03
~
TRFFC04 TRFFC05

1
TRFFC07

1·,1
TRFFC08

+
TRFFC09

1=·
·· ·.,
'
TRFFClOA TRFFC1 0B TRFFClOC

50 1,,--:::! ___..)

TRFFC11 TRFFC12 TRFFC13 TRFFC14 TRFFC15 TRFFC16

TRFFC17
• •
TRFFC18A TRFFC18B
11
TRFFC19A TRFFC19B TRFFC20

Writing
-----·•..
~----i
'-l.i/ 4

BOOK01A BOOKOl B BOOK02 BOOK03 BOOK04 BOOK05

BOOKS01 BOOKS02 BOOKS03 BOOKS04 BOOKS05


'
ERASEOl

·~••
í> k:;1..1,--

ERASE02 NOTEOl NOTE02 NOTE03 NOTE04 NOTE05

Microsoft Visual Basic Programmer's Guide


Appendix B lean Library 409

NOTE06 NOTE07 NOTE08


e, e,
NOTE09 NOTE10
Q
NOTE11

.,,/?''•..,
~t:
~ '-.
~-~
NOTE12 NOTE13 NOTE14 NOTE15 NOTE16 NOTE17

~,~--~
~ Y./
~ .··

NOTE18
F-
--
PENOl PEN02
/
PEN03
/
PEN04
/
PEN05

PEN06 PEN07
'
PENCILOl PENCIL02 PENCIL03 PENCIL04

PENCIL05 PENCIL06
' ' ' '
PENCIL07 PENCIL08 PENCIL09 PENCIL10

PENCILl 1 PENCIL12
' '
PENCIL13 PENCIL14 PENS01 PENS02

PENS03 PENS04

Microsoft Visu al Basic Programmer's Guide


Glossary

This appendix describes technical terms or terms that have a specific meaning with regard to
Visual Basic. Note that property names and event names are not included below, but are
listed in the Language Reference and online Help.

A
access key A key that enables the user to open a menu, or select a control by typing a
designated character while holding down the ALT key. In contrast, a shortcut key enables the
user to execute a menu command by press ing a function key or key combination (such as F:i
or CTRL+A).

active The condition of an error trap when control of an error-handling routine actually
branches into the trap.

ANSI character set American National Standards Institute (ANSI) 8-bit character set used
by Microsoft Windows that enables you to represent up to 256 characters (O -255) using
your keyboard. The ASCII character set is a subset of the ANSI set.

application A collection of code and visual elements that work together as a single
program. Developers can build and run applications within the Visual Basic environment,
while users usually run applications as exec utable files outside Visual Basic.

application name A unique name given to every application that can be a server in a DDE
conversation, usually the executable filename without any extension .

argument A constant ora variable passed to or from a procedure.

array A group of variables that share a co mmon name. Each element of the arra y has a
unique index number that identifies it.

ASCII character set American Standard Code for lnformation Exchange (ASCII) 7-bit
character set widely used to represent letters and symbols found on a standard US keyboard.
The ASCII character set is the same as the first 128 characters in the ANSI character set.

assignment statement A statement - such as Te x t 1 . Te x t = "o u r na me" - that


assigns a value to a variable ora property reference.

attach The action of writing code associated with a control or form. Event procedures are
said to be "attached" to a form or control.

Microsoft Visual Basic Programmer's Guide


412 Part 5 Appendi xes

B
binary access A type of file access (typically using the statements Open, Close, Seek,
Input$ ) th at makes no assu mptions about individual bytes in a fil e

bit The sma lles t unit of data a computer can store, equal to 1 or O.

bit-field argument An argument that returns information in individual bits. Each bit
indicates whether a certain condition is on or off.

bitmap An image made up of pixels on the screen, stored as a collection of bits, in whi c h
each bit corres po nds to one pixel. On color systems, more than one bit corresponds to eac h
pixel. Usua ll y has the fil e ex tension .BMP.

bit-wise comparison A co mparison of corresponding bits in two integers.

Boolean An expression that can be evaluated as true or fal se. The Integer data type can be
used to rep rese nt Boolean values, with - 1 representing True and O representin g False.

break mode The state of Visual Basic when a running program has temporarily halted . In
break mode, yo u can use debugging tools, continue execution, return to design time, or
restart exec ution of the app]ication from the beginning.

breakpoint A statement at whi ch Visual Basic automatically stops exec ution , putting the
application in break mode.

e
Caption The propert y you se t to specify the text di splayed on a co ntrol or form .

check box A co ntro l used to representan option (on/off, true/false) that the user can se t or
c lear by clickin g. An X in a check box indicates that it is selected .

client An app li cation that receives data through DDE.

Clipboard The temporary storage area used by the operating environment to store text,
graphic s. and othe r data. The data is transferred with Copy and Paste commands .

Clipboard object An objec t accessed with the keyword Clipboard and used to manipulate
text and grap hi cs in th e ope rating env ironment's Clipboard .

code A ge nera l term fo r state ments written in the Visual Basic la ng uage.

code template The first and last lines of a procedure (Sub and End Sub). Nothing is
exec uted unti I yo u add a stateme nt. .

Code window The Vi s ual Basic window for entering, editin g, and debugging code. One
Code w indow ca n be ope ned for eac h fo rm and modul e.

Microsoft Visual Basic Programmer's Guide


Appendix C Glossary 413

Color palette A window used to change the colors of a form or control orto set upa
custom color scheme.

combo box A control, similar to a list box anda text box combined, in which the user can
either enter values or select items from a list.

command button A control the user chooses to carry out a command or action. Command
buttons are sometimes called "push buttons."

comment Text embedded in code but ignored by Visual Basic, used to explain how the
code works. Each comment line starts with an apostrophe (') or the keyword Rem follow ed
by a space.

constant A value that does not change during program execution , inc luding literal and
number strings and symbolic constants, designated using the Const state ment.

control A graphical object placed on a form such as a text box and comrnand button . Each
control has its own list of recognized properties and events.

control array A group of controls that share a common name, type, and event procedures.
Each control in the array has a unique index number that you can use to determine which
control recognized the event.

control structure A Visual Basic statement that controls loops and decisions in code.
Examples are lf... Then ... Else, Case Select, Do loops, and For loops.

conversation An exchange of information between two application s via DDE.

current statement The next statement to be executed during debugging . In Visual Basic ,
thi s state me nt is indicated by a rectangular outline.

custom control files Files that provide new types of controls to the Visual Basic
development environment and supply new capabilities to Visual Basic applications .

D
data type The attribute of a variable that determines what kind of data it can hold.
Supported data types include Integer, Long, Single, Double, Currency , a nd String . Special
data types include Form, Control, and user-defined types .

DDE Dynamic data exchange. Within Visual Basic, DDE events and properties make it
possible for your application to communicate with other Windows app li ca tion s.

Debug object An object accessed with the keyword Debug and used to se nd output to the
Immediate window. ·

Microsoft Visual Basic Programmer's Guide


414 Part 5 Appendixes

debugging The process of finding errors in program logic . Debugging in vol ves running
specific portions of your applications and analyzing data at each point.

declaration Nonexecutable code that names a constant or variable and defines its attributes
(such as data type).

Declarations section A collection of variable declarations and constant definitions used to


declare form-level (or module-leve!) variables and constant defi nitions shared by all
procedures in the form (or module).

default A value that is assumed if no other value is specified. For example, if you don ' t
assign a value to the Enabled property, it is True by default.

design time Any time when you are building an applicati on in the Vi sual Bas ic des ign
environment. In contrast, during run time you run and interact with the application as a user
does.

directory list box A control that di splays a hierarchical list of directories . A directory list
box enables the user to select directories and paths at run time .

DLL Dynamic-link library. This is a set of routines that extends the normal capabilities of
Visual Basic. DLLs provide the means to cal] routines written in another language as well as
low-level operating-environment routines.

drag and drop Features that enable the user to drag a control and drop it on a form or other
co ntrol, using the mouse.

drive list box A control that displays a li st of ali val id drives in the use r' s sys te m. A drive
li st box finds and switches between valid di sk drives at run tim e.

E
enabled A term used in Visual Basic to describe settin g an error trap ("Enab led" is also a
property name) .

error trapping The ability of Visual Basic to intercept errors.

event An action recognized by an object (form or control) and for which you can write
code to respond to. Events may occur as a result of a user action (s uch as clicking a mou se
or pressing a key) orbe tri ggered by the system.

event-driven A term that describes th e programming model in Visual Basic. Unlike


applications written in procedura l languages, a Visual Basic application consists of code that
re mains idle until called upon to respond to specific user-caused or sys tem -caused events.

event procedure A procedure th at Visual Basic in vokes in res ponse to a spec ific eve nt,
whi ch may be caused by th e user or triggered by the sys te m.

Mic ro soft Visual Basic Programmer's Guide


Appendix C Glossary 415

executable code Code th at performs a task at run time, such as carrying out a command or
retuming a value. In contrast, nonexecutable code defines variables and constants.

executable file An appli cati on created in Visual Basic that can run outside the Visual
Basic environment.

executable statement A statement that Visual Basic translates into a specific action at run
time. Most Visual Bas ic statements are executable. The main exceptions are declarations,
constant definitions, comments, and user-defined type definition s.

expression Any combinati on of vari ables, constants, function s, and operators that Visual
Basic can evaluate to yield a single value.

F
file list box A control th at displays a list of filenames selected according to their attributes .
A file list box fi nds and specifies fil es to be opened, saved, or otherwi se manipulated at run
time.

focus The capacity to receive user input through the mouse or keyboard. For example,
when a user types a string, it appears in a text box only if the text box "has the focu s."

form A window or di alog box that yo u create with Visual Basic.

form code Ali the procedures and declarati ons attached to a form . (This includes
procedures th at res pond to an event for any of the controls on the fo rm). Form code is stored
in the same fil e as the fo rm itself.

form -level variable A variable recogni zed by all procedures attached to a form .

frame A control th at appears as a rec tangle. A fra me can be used to group option buttons or
other controls.

Function procedure A procedure th at retums a value and can be used within an expression .
Function procedures are dec lared wi th the Function key word .

G
general procedure A procedure that is not executed unless another procedure calls it. In
contras t, an event procedure is in voked automatically in response to a user or system acti on.

global The broadest possible scope, in whi ch a variable or constant definition is recognized
by the entire applicati on. Procedures in a modul e can also be said to have global scope.

global module A special modul e th at contains vari abl e, type, and constant information
recogni zed throu ghout the entire applicati on. Unlike other modules, the global module
cann ot contain procedures . Eac h projec t co ntains exactl y one global module.

Micro soft Visual Ba sic Programmer's Guide


416 Part 5 App endixes

grid The dots or points, measured in pixel s, on the Form window when you ' re in design
mode. Usi ng the grid ensures th at control s are positioned uniformly .

H
handle A unique integer va lue used to ide ntify and access a window or control.

hierarchical menu A menu that di splays a hierarchical list of items, including one or more
subm enu s.

horizontal scroll bar A control that appears as a scroll bar along a horizontal (left to ri ght)
ax is. lt is not attached to tex t o rto a window, but is useful asan alternative way of getting
input and d isplaying outpu t.

hot link A DDE link betwee n two applications in which changes m ade to data in the server
application are immediately reflected in the client applicati o n.

icon A graphical representation of an object or concept, commonly used to represent


minimi zed applications in Microsoft Window s and Presentation Manager. Essentially a
bitmap with a maximum size of 32x32 pixel s. Icons have the file extension .ICO.

idle loop A loo p that exec utes state ments on ly when nothing else in the environment
requires im medi ate attention.

lmmediate window A wind ow used to exec ute in dividu al lines of code, ofte n for the
purpose of deb ugg in g. This w indow ca n be used only in break mode.

index An integer valu e th at g ives th e position of an element in an array ora co ntro l array.

initialize To set at th e startin g va lu e or condit ion.

insertion point The pl ace where text is inserted whe n yo u type.

items Refe re nces to data th at is meaningful to both appli cation s in a DDE conversati on.

invocation path The chain of proced ures that has been invoked to anive at the c urrent point
of exec uti on.

J
1ump In on line Help, an underlined word yo u cli ck to go to a topic related to th at word.

K
keyword A Vi sual Basic statement , method , fun cti o n, or operator. A lso used to refer to a
sea rch term in o nline He lp.

Microsoft Visual Ba sic Programmer's Guide


Appendix C Glo ssary 417

L
label A control that consists of text (called a "caption") that the user cannot directly
change. The term " label" also refers to the target of a GoTo or GoSub statement. Within
code, specific lines can be identified with either a line number ora line label. ·

link A synonym for a DDE conversation.

list box A control that provides a list of choices.

local The smallest possible scope, in which a variable or definition is recognized onl y
within the proced ure in which it appears .

logic error A programming error that can cause code to produce the wrong results and/or
halt exec ution . May be caused by mix-ups in variable names or wrong variable types,
e ndl ess loops, flaw s in logical comparisons, or array problems.

logical centimeter, logical inch The length of an ítem which is one centimeter or one inch
lon g when printed. The actual size of a logical centimeter on screen may vary dependin g on
th e s ize and resoluti on of the user's monitor.

loop A programmin g construct that repeats a group of statements.

M
menu A list of commands, available at the top of a form or window , that is di splayed when
th e use r clicks th e menu name. You use the Menu Design window to create menus.

menu bar A bar that displ ays the names of menus available for use in the active window.

menu command A command name that appears on a menu when the menu is open .

menu control An individual menu item - either a menu name, command, or separator bar.
You use the Menu Design window to create menu controls; ali other types of controls are
created with the Toolbox .

menu name The name of a menu that appears on a menu bar. Clicking a menu name open s
a me nu and di splays its commands.

metafile A Windows fil e that stores a graphical image in term s of graphics objects (lines,
circ les, polygons) rather than pixels; it usuall y has the extension .WMF. A metafile
preserves an image when resized better than a bitmap

method A Vi sual Basic keyword similar to a function or statement, that always acts on an
object (a form , control, or one of th e special objects Printer or Clipboard).

Microsoft Visual Basic Programmer's Guide


418 Part 5 Appendixes

modal A type of fo rm th at retains the focu s until closed. Most modal fo rm s are dialog
boxes o r warnin gs .

modeless A ty pe of form th at is not modal. A modeless form permits the use r to do sorne
work o n th e form , move the focus to another form , then move back to the ori ginal form .

module A co ll ec ti o n of procedures and data declaration s stored together in a s in g le fi le and


not att ac hed to a form . Procedures in a module are recog nized throu ghout an application .

module-leve! variable A vari able declared in the Dec larati ons sec ti on of a module and
shared by ali the procedures in that module.

N
nested A co ntrol structure is nes ted when it is inside another control stru cture.

o
object A general term fo r fo rm s, controls, and the special objects Clipboard , Debug.
Printer and Screen .

Object box T he drop-dow n list box at the top left of the Code window th at li sts for ms,
co ntrols . and "(ge neral)." "

operating environment T he working environme nt under w hi ch Vi sual B asic and


app licat ion-. crea ted with Vi sual Bas ic can run (M icrosoft Wind ows or Present ati on
Ma nage r ).

operato r A wo rd o r sy mbol (s uch as a plus sig n) used to co mbin e or manipul ate va lu es in


an ex press ,o n.

option button A co ntro l simi lar to a chec k box , exce pt th at it alway s wo rks as part o f a
g ro up. Th e user can select onl y one opti on button fro m a gro up. Opti o n butto ns are
so met imes ca ll ed " radi o buttons."

p
persistent graphics O utpu t fro m graphics meth ods (Circle, Cls, Line , Point, Print, PSet)
th at is aut o mat ica ll y retai ned when the fo rm is red raw n. Graphics are " pers istent' ' if th ey are
d rawn whc n the A uto Redraw property is set to True (- 1).

picture box A cont ro l th at contai ns a graphical im age (bitm ap, icon, or metafil e) . Pi ctu re
boxes a lso can co ntain o utput of graphics statements, tex t written w ith a Print meth od , and
o pti on bu tto ns.

pixel A n abb rev iati o n for ·• picture element"; a dot th at re present s the s mall es t g raphi c uni t
o r meas ure me nt o n th e sc ree n.

Microsoft Visual Ba sic Programme r's Guide


Appendix C Glossary 41 9

pointer The too! at the top of the Toolbox th at rese mbl es a mouse pointer, used to selec t,
move, or resize a control.

poke A DDE term descri bing attempts by the client applicati on to send data to the server
appl ication.

print zone A print area 14 columns wide, where a column is the average size of a charac ter
in the font and font size you specify. With the Print method, a column causes output to start
at the next print zone.

Printer object A drawing obj ec t accessed with the keywo rd Printer. Used in code to
contro l text and graphics printed on a page and to di rec tl y send output to a printer.

procedure A seq ue nce of Visual Basic statcmen rs exec uted as a unit, so metimes refe rred to
as a "subroutine" or "fun ction" in other programmin g languages. The term "procedure"
refers to both Sub and Function procedures.

Procedure box The combo box at the top right-of the Code window that lists procedures.

procedure stepping A debugging technique that enab les you to trace code execution one
statement at a time; does not trace into procedure call s.

project The collection of source files (forms and modul es) that make up an applicati on.

Project window A Visual Basic window that di splays ali the forms and modul es in a
proj ect or applicati on.

property A named attribute of a form or co ntro l that yo u set to defi ne one of an objec t's
characteri stics (such as size, color, scree n location) ora n as pec t of its behavior (whether it is
enabled or not).

Properties bar The V isual Basic too! for viewing and setting properti es at design time. The
lis t of applicable properti es changes dependi ng on the type of co ntrol or form that's selec ted.

Properties list box T he box at the left of the Properties bar that di spl ays a li st of properties
fo r the selected objec t.

R
random access A type of fil e access (typ icall y usi ng the state ments Type ... End Type,
Open, Put #, Len, Get$) used for fil es whose data is organi zed into di sc rete record s of fi xed
length. Y ou can access the records in an y order.

reserved word A word that has special mea ning within Visual Bas ic, including predefin ed
state ments, functi ons, methods, operators, and Visual Bas ic prope rty and eve nt names.

run time Any time when th e appli catio n is runn ing. During run ti me, yo u can inte rac t with
an ap plicati on as a user wo ul d. In contrast, during design ti me you build the applicati on.

Micro soft Visual Basic Programmer's Guide


420 Part 5 Aprendixes

run-time error An error that Visual Bas ic can detect onl y when an application is runnin g.

s
scope The attribute of a vari able or procedure that determines how much of the application
will recognize it.

Screen object A n object accessed with the keyword Screen and used to activate a
specified form or control at run time.

separator bar A bar that divides commands into logical groups on a long menu.

sequential access A type of fil e access (typically using the statements Open, Line
Input#, Print #, Input$, Close) used fo r tex t files and variable- length record files. The
reco rds must be accessed in a parti cul ar o rd er. Numbers in a sequenti al-access fil e are
represented by character strings, just as words are.

server An application that provides data through dynamic data exchange (DDE), at the
requ est of a client application .

server link A DDE link in which the client application requests data from the server
application .

setting The value of a pro perty (for exa mple, the setti ng of the BackColor property could
be white) .

Settings box T he box at the middl e of the Propeni es bar that di splays and accepts c hoices
for propert y settin gs.

shortcut key A fu ncti o n key or key combi nati on - such as F5 or CTRL+A - th at executes
a co mm and . In co ntrast, an access key enables the use r to open a menu , or select a control by
typing a designated letter in the captio n whi le pressing the ALT key.

single stepping A debuggin g tec hnique that enables yo u to trace code executio n one
state me nt at a ti me .

sizing handle One of the small squares di splayed on the edge of a control when it is drawn
or selected. You use the sizing handles to resize the con trol.

source An object the user drags. Thi s control can be any type except a menu or tim er.

statement A sy ntac ti cally compl ete unit that ex presses one specific kind of action ,
declarat ion. or definiti o n. Normall y, one line in a procedure or Declarations section ,
alth o ugh yo u can use the colon (:) to put more th an one statement on a Iine.

static A loca l variable or arg um ent whose va lue is preserved in a procedure , e ither
dec lared wi th th e key words Static or Dim, or dec lared implic itl y.

f..1/croso ft Visual Basic Programmer's Guide


Appendix C Glossary 421

submenu A menu that opens when a menu item inside a higher-level menu is selec ted.
Submenu items are indented to indicate their hierarchical position or leve!.

Sub procedure A procedure that does not retum a value, and is declared with the Sub
keyword. All event procedures are Sub procedures .

syntax The prescribed order and punctuation for putting programming language elements
into statements that are meaningful to Visual Basic.

syntax checking A Code window feature that ch~cks your code for correct syntax every
time you enter a line.

syntax error An error in following the grammatical structure of the language, sometimes
caused by a simple typing mistake .

T
tab order The order in which the focus is moved from one control to the next by pressi ng
the TAB key .

target An object (either a form or control) on which the user drop s the source (the control
being dragged) . This object recognizes the DragDrop event.

text box A control that provides an area for the user to enter text. The application can
manipulate the contents of a text box by using the Text property. Text boxes are so metimes
ca lled "edit fields. "

timer A control that responds to the passage of time: specificall y, a period speci fi ed by th e
timer's Interval property. A form can have multiple timers, each with its own interval. The
timer control is the only type of control that has no graphical properties .

title bar The bar that appears at the top of a form and displays its caption .

Toolbox The set of tools you use at design time to place controls on a form. Usually
ap pears as a window with icons at the left of the screen.

topic The subject of a dynamic data exchange (DDE) conversation between two
applications.

type-declaration character A character used as a suffix (% , & , !, #, @, or$) , in addition to


let ters and numbers , in a variab le name, and which identifies the data type.

twip One-twentieth of a point. There are 1,440 twips to an inch and 567 twip s to a
centimeter. In Visual Basic , a twip is implemented as 1/1440 of a logical inch .

Microsoft Visual Basic Programmer's Guide


422 Part 5 App end ixes

u
user A person who run s a Vi sual Basic applicati on after it is fini shed. This person may or
may not be the same as the applicati on designer.

V
variable A place to hold data that can change as the application runs. Each variable has a
unique name that identi fies it within its leve! of scope.

vertical scroll bar A control that appears as a simple scroll bar along a vertical (up and
dow n) ax is. It is not attached to text or to a window, but is useful asan altemati ve way of
ge tting input and dis play ing output.

Microsoft Visual Basic Prog rammer's Guide


lndex

In addition to pointers to information in the Programmer 's Guide, thi s index includes pointers to related
information in online Help on menu commands, objects, the interface, and step-by-step instructions for usin g
Visual Basic . Each pointer to Help lists the keyword you should use when searching through Help.
For furth er informati on on a Vi sual Basic language keyword, property, event, or method li sted in the index
(and for informati on on those not covered in the Programmer's Guide), search Help by name, or refer to thc
Language Reference .

Symbols Relati onal operators (cont inued)


> (greater than) 87 - 88, 98
Arithmeti c operators >= (greater than or equal to) 87 - 88, 98
/\ (exponenti ati on) 75, 99 T ype-declaration characters
* (multiplicati on) 75, 98 ! Single 83
+ (addition) 98 # Doubl e 83
/ (di vision) 75, 98 $ String 83
\ (integer di vision) 98 % Integer 83
- (negation, additi ve) 98 & Long 83
- (subtrac tion) 98 @ Currency 83
Mi scell aneous
# (number sign), form atting numbers 75 , 156
$ (da ll ar sign), fo rmatting numbers 156 A
& (ampersand) Accelerator box 120
assignin g access keys 120 Access keys
use with hexadec imal and octal nu mbers 80 ass igning 120- 12 1
'(apostrophe) , com me nt sy mbol xv , 80,4 13 defin ed 120, 4 11
() (pare ntheses) tab a rder 120 - 12 1
call s to Function procedures 80 , 96, 396 Search Help for access keys
use with operators 75, 98 Acti ve, defi ned 4 1 1
, (comma) Ac tive applicati on 376
num ber fo rmats 128 Ac ti veControl p roperty, Scree n obj ect 266
Print method and 15 1, 154 Add Fil e comm and (File menu)
separating argu ment na mes 95 use of 44
: (col on), separating state ments 8 1 Sea rch Help fo r Add F il e command
; (semi co lon), Prin t method and 15 1 - 152, 239 Addltem method
= (equal sign), in state ments 8 1,258 li st boxes and combo boxes 135 - 136
? (questi on mark), printing 23 6, 239 syntax 135
[] (bracke ts) , sy ntax conve nt io ns xiii Additi on (+) operator 98
( } (braces), sy ntax co nve nti o ns xiii A larm Clock appli cation
1 (vertical bar) , sy ntax co nventi ons xii i code 27 1- 272
• (line-continu ati o n character) xrn , xv1 See also Digital Clock applicati on
Re lati onal operators A li as key word 38 1
< (less than) 87 - 88, 98 Ali gn to Grid command (Edit menu ) 55
<= (l ess than or equ a l to) 87 - 88, 98 ALT key
<> (not equ a l) 87 interrupting DD E 360
= (equ ality) 88, 98 tes ting fo r, key board handle rs 27 5, 277 - 278
use with access keys 120
424 Ampersand

.\rnpcr<,and (&) Appli cations. sa mpl e (co ntinued)


ª"'ign in g acccs-. key-. 120 Project Planner 106 - 107
Long type-declaration charac ter 8 1. 83, 115 Record Ed it or 336 - 350
u'.->c \\'ith hexadec im al and oc tal numbers 80 Rock 'n ' Rol! 2 17-226
\ ,1 .1P..\I. time conve rsion 270. 271. 272 Scri bble 199 - 20 l. 204 - 205
...\nd opera1or 88. 98 Temperature Conve rter 147 - 148
.-\ngle', Tex t Ed itor 320- 33 1
ca lcu latin g in radians ,·s. degrees 19 1, 192 Try Menus 109- 11 2
rneasurin g in Visual Bas ic 19 1- 194 See a/so Code examples
...\nirnat ion effec1 A rchi ve propert y. fil e li s1 box 3 14
Drav. Modc 7 186 Ares
1ogg lin g he1wcen two icons 165 Circle method sy ntax 193
-\\"S I charac1e r, drawing 19 1. 193 - 194
defined -111 Argument
Ke, D011 n. K C) L'r C\Cnls 277 definecl 80. 41 1
Kc, Pre,, e, cnt 275 passi ng by re krencc 97
.-\rostrophc ('). commen t sy mbol xv. 80. 4 13 pass ing by valuc 97
...\pp Activa1e ,1a1emcn 1 376 A rithmeti c operators
...\ppend moc.lc. Open sta tement 3 17.3 18 li st of 98
...\ppli ca ti on orcl er of prececlen ce 75, 98
definec.l 36. -11 1 Arrays
de,ign ti¡b n8 - 229 control arra y See Control arra y
cxi tin g rrom 226 dec laring 253 - 256. 397
pan,oJ" .1,7 defin ecl 252 . 253.4 11
, lart up form or module DLL rou1ines and 383
de, igna11ng 220 - 221 dynarnic 255 - 256. 397
Seuu I, He/¡¡ .for ,1artup form fixecl 253. 397
,1ep, in uc,11111g Seorch Hc,f¡;furcrea te appli cati on multidimensional 255
Sec u/10 \1ul11plc form app lications two-d im ens io nal 255
\¡1p lic111on \l.1n.1gL' r of, ari ablc~ 25.1 - 256
adc.ling L·,imm,,nd, 11 7- 118 Sean-/1 1-/elp .for arra y
delctin g rnmma nc.l , 11 7. 119 - 120 Arrow icons (!co n LibraryJ 400 - 40 1
..\rp lication nc1n1L· ( DDE) See DDE app li ca1ion name Arrow keys. key board hand lers and 275
\rpliL·a1 ion,. ,;imple As Any keywo rd ]8 1. 385
,-\larm Clud. 27 1 272 As Control kcyword :248 - 249
r\ppli c11io111\ lan,1ger 117 - 120 As keyword 95
Calcu lator Ase functi on 127 - 128
de,cri pi 10n or 0 ASC II c harac 1ers
St'e o/\fJ l11,·c, 1mc11t Calc ul ator clefined 127.4 11
Carc.lfi le 9 recognited by Key Press 126
Click -1\ -Line 108 ASC II formal. sav ing in 45, 73
Digital Cl od 270 - 271 ASC II Z strin gs 382
File lnlo 305 .11--1. 328 Assignment statement
Hel io. 11·orld' .16 - ~2 defin ed 8 1.4 11
kon \,\' ork, lJ performing ca lculalion s 82
111 ,·e, 1mcnl C,dcu lalor rc1riev ing val ues of propertie s 82
adv,,nccd kc1 1urcs 89. 97 se ttin g va lu es of properti es 8 1, 237 - 238
codc 66 - 75 storing data in va ri ab les 82, 237 - 238
in1 crf.icL' ..¡<; _ 52 sy nta x 8 1
propc rt ic, 61 - 6-1 Asteri sk (* J. mul tipli cati on sym hol 75, 98
Lwnch Pad 208 - 30-1 Al sig n ((Q ). Curre ncy lypc-dec laration characler 83
Numhc r S)slcm 11 3 - 11 5. 130 - 13 1

Microsoft Visual Basic Programmer's Guide


Button 42'.

Attachin g code Bit


defined 67 - 68. 4 11 bit-w ise co mpari so n~ 99. 412
first examp le 69 - 72 Bu/Ion argument , mouse events 202 - 204, 206
Search Help fa r attach code defi ned 99,4 12
AutoRedraw property Shift argum ent, mouse events 206, 277 - 278
creating persistent graphi cs 176 Bit-field argument. defi ned 196 , 4 12
prin tin g fo rms 159 Bit-w ise compari so n, defined 99, 4 12
AutoS ize property Bit-w ise operators 98
label s 168 Bitmap
picture boxes 164, 168 .BMP fil e ex tension 162
data formal (Cl ipboard ) 267
defined 412
B BLOAD keyword 396
B opt ion. Line meth od 188 .BMP fil es 162
BackCo lor property Bo ld, font formal 150
dcfined 142 Boo lean
graphic s and 177, 18 1 express ion, defi ned 87 , 4 12
PSet method and 18 1 properties 88. 107
BAC KSPACE key True/Fal se va lu e~ 99. 107
ASCII number 127 BorderStyl e propc rt )
keyboard hand lers and 275 form s 2 18, 2 19
Bar See M enu se parator bar labe ls 147
Base 8 See Octal numbers Bounds
Base I O See Dec im al numbers array s of variabl es 254. 255. 256
Base 16 See Hexadecim al numbers co ntrol array s 253
Basic See Mi croso ft Vi sual Basic Bo x
Basic Profess ional Development Sys tem See Mi crosoft drawing 188 - 189
Basic Profess iona l Development Systern fil! sty les 18,'
BASJ CA language Search He/p .fiJr dra\\ box
adapting codc !"mm 391 - 398 B races ( l l ). sy nta, urn1 cnt ion~ x 111
co mpared wi th Vi sual Basic 8-9. 392. 394 Brackets ([]). synta, conve nti ons x 111
scope of vari ab les 394 Break command ( Run men u)
Bcep statement use of 229
creatin g beep sound 95 Search Help.fin Break co mm and
use in data va li dation 126 Break mode
B i nary access defined 229.-!12
compared w ith ran clom access 350 - 35 1 sw itchin g to 229. 230 - 233
defined 3 16 -3 17, 350, 4 12 use of 230
See a/so Bin ary file Search Help jor break mocle
Bin ary fil e B reaking exec uti on. tcc hniqu es 229 - 233
BinaryCopy Function procedure 35 1 -352 Breakpoint
fil e pointer 352 clearin g 232 -233
Get and Put statement s used wi th 350 - 35 1 creatin g w ith Stop ~tatcments 233
open in g fil es in binary mode 3 17, 3 18 - 320, 350 defined 23 0. -l l 2
overview of file access 3 16 - 3 17, 350-35 1 se ttin g 231
Seck statement used with 352 Search Help j()r breakpo int s
whe n to use 3 16, 350 BSA VE keywo rd 396
Binary forma l , sav ing in 45, 73 Buffer
B i nary mode, Open stateme nt 3 17, 3 18, 350 DLL routinc ~ and 383
B inaryCopy Fun cti on procedure 351 -352 size for random -accc~s fil es 334
Button See Command hutton control

Microsoft Visual Basic Programmer's Guide


426 Button argument

B.11/ 0 11 arg um ent Check marks


defincd 196.202 addi ng to menus 113 - 11 5
tes tin g mouse button statu s 202-204 when to use 1 13
F.,, \'a l keyword Checked property . rnenus 11 3 - 115
pass i ng argument s by va lue 97, 380 -38 1 Check ew Lines Sub procedure 330 - 33 1
, 1 ntax 95 Chr$ function 127
U\e w ith DLL routin es 380 - 38 1, 382,386 Circle. drawing 186, 189 - 190
use w ith handl es 386 Circ le method
aspect argu ment 190 - 191
I" described 177
J
drawing ares 19 1- 194
:Jnguage drawing ci rcl es 186.1 89 - 190
C stri ng\ and DLL routi nes 382 drawing el lipses 190 - 191
co mparcd w ith Visual Basic 8 end argument 190. 193 - 194
r .:i d ilat or negative numbers with 193 - 194
.ipplica ti on 9 mdiu:, argu111ent 189 - 191
See a/so ln ves trnent Ca lcu lator start argum ent 190. 193 - 194
C.-\LL ABSOLUTE keyword 396 Step keyword 189
C -\LLS keyword 396 sy ntax 189. 190
C..: nce l butt on 102 C lea r A li Breakpoints co mm and (R un M enu
C .:p tio n property commands) Search f-fe/pforCle ar Al i
ass ignin g access keys usin g 120 Breakpoints command
Jcfi ned 38 . 4 12 CL EA R keyword 396
fo rm s 63 C lear method 266
labe ls 63 , 147 C lear tec hniques See Clcar method: C ls rnethod
,ctt i ng via code 12 Click event
,ct ting via Properties bar -+0. 6 1 check box 132. 133
i _,,·d filc application 9 combo box 139
r _,;-e t("). expo nentiation syrnbo l 75, 99 co mmand button 1 02
. n:1gc -rcturn charac ter :n
li,t boxc\ 1 Jx I
Tcx tH eight method and 15 3 menu s 111
'i"ee o/so Ncw lin e character option button 129
< .: ,e Else clausc 9 1 pi cture box IO?.
l .- i,i11s/Fa hrcnhcit, converting 147 - 148 writing cli ck e,ent~ 7 1 - 72
r :. BITM AP 267. 367 C li ck-A-Line app li cation 198
< :. D IB 267. 367 C li ent appl ication
C : _LINK 267 defined 354. 4 12
< :._ \ I ETAFIL E 267, 367 See a/so Clicnt lini.-
C :.. _ TEXT 267,367 Cl ient link
< =-J -\ 1 kc yword 396 crcating 356 - 157
( -- ,t llgC CVC !ll defined 356
co mbo box es 139 evc nt s 362 - 163
, L-ro l I bars 141. 142 propeni cs 158 - 360
< -- :?c i.- box co ntro l See a/so DDE (dynamic da ta excha ngc)
Clid e, cnt 132. 133 Search lle/pji>r link
dc l ined 132 , 4 12 C lipboard
KcyPrcss evc nt 133 defined 412
pro pcnic s. cvc nt s, and method s ( li st) Seorch 1-fe/p copy in g bitmap~ to/from 267
/ilr check box copy in g graphics to/frnm 162. 267
l"oo lbox loca ti on 48 copying metafi lc to/ from 266
\ 'al uc propc rt y se ttin gs 132 copyi ng tc"t to/ from 265 - 267
11 ork i ng wi th u ser input 132- 133

r.1 crosoft Visual Basic Programmer's Guide


Code examples 427

Clipboarcl appli ca ti on 365 Cocle exa mples ( co111inuec/)


C lipboarcl obj ec t Bin aryCopy Fun cti on proceclure 351 - 352
C lear methocl 266 Calcul ator See In ves tment Ca lcul ator
creatin g copy, cut, ancl paste commancl s 265 - 266 ca lcul ating logarithm s 96 - 97
creating cl ynami c paste- li nk capabiliti es 267 , ca lcul ating squares ancl square root s 111 - 1 12
365 - 368 Cli ck-A -Lin e applic ati on 198
elata format s usecl by 267 col or
clefinecl 265,4 12 in vertin g color of rectangle 384 - 385
GetData meth ocl 267 invertin g while clragging control s 2 11
GetForm at methocl 267 setting vi a scroll bar 142- 143
GetTex t meth ocl 265 - 266 convertin g lowercase to uppercase 105, 127, 13 3
SetData meth ocl 267 CopyFile Functi on proceclure 334 - 335
SetTex t met hod 265 - 266 copy ing text from/to text boxes 104
Sea rch HelpforC li pboarcl object creating control array 170 - 17 1
CLIPBRD .EXE 365 creatin g copy, cut, ancl paste co mm ancls 266
Cl oc k DDE
Alarm Cloc k application 27 1- 272 creatin g DDE copy commancl 368
Di gital C lock appli ca ti on 270 - 27 1 creating DDE paste lmk commancl
Close statement 366 - 367
fil e access type ancl 3 16, 3 17 creating link s with Exce l 359, 360, 370
fil e number ancl 3 17 error handling 373 - 375
C ls methocl limiting clients 363
A utoReclraw settings effect on 176 setting respon se to DDE 361
clearin g draw ing area 177. 180 - 18 1 startin g appli cati ons 369
controlling print outpul 152. 177 upcl atin g links 370 - 37 1
clefin ecl 177 cle terminin g climensions of scree n or printer 386
sy ntax 180 Di gital Clock appli ca ti on 270 - 27 1
/CMD 17 cl isp lay ing date ancl tim e 112
Code DLL routin e, ca l lin g 379. 384 - 385
au ac hi ng code draw ing
contro ls 69 - 72 ares 193 - 194
clefin ed 67 - 68, 4 11 boxes 188 - 189
fo rm s 69 - 70 circ les 186, 189
clefi ned 4 12 ellipses 19 1
editin g cocle 70 lin es, varying w icl ths ancl sty les 184, 185
introclucti on to writ ing cocle 40 - 43 , 67 - 72 polygons 183
sav in g 45. 73 rectangles 384 - 385
settin g prope rti es vía code 42. 64 spokecl pattern 183
temp late error handling
clefin ed 4 1, 4 12 C heckTxtFil es Sub procedure 280 - 28 1
cli spl ayed 68, 70 ConfirmFil e Fun cti on proceclure 290 - 292,
w hen to use 40. 66 - 67 322,337
Sea rch He /p far attach cocle: copy cocle: ecl it cocle; DDE errors 373 - 375
fi nd eocle clelayecl 292 - 293 , 304
Cocle exa mpl es (on l in e H elp) Di viclelt Functi on proceclu re 285
copy ing ancl run ning 29 - 3 1 Fil eErrors Functi on proceclure 288- 290
Sea rch Help fo r cocle exa mples turning off 294 ·
Cocle exa mpl es ( Programme r's Cuide ) Y erifyFile Functi on proceclure 285-286
A larm C lock appli ca ti on 27 1- 272 Fi lelnfo appli cati on 305 - 3 14, 328 ·
animation effects 165. 186 Fi leüpener Function proceclure 3 18- 320
A pp l ica ti on M anager 117 - 120 H eli o, worlcl 1 appli ca ti on 36 - 42
bce p 95 initi ali zing an array 254, 255

Microsoft Visual Basic Programmer's Guide


~28 Code examples

:ode exa rn ples (co n1 i11 ued) Co lor ( continued)


In,·es trnent Ca lcul ator spec ifyin g (co ntinued)
advanced features 89 . 97 RGB fu nction 179
code 66 - 75 sc ro ll bar 142- 143
contro ls and propert ies 49 - 52, 6 1- 64 Sea rch He/p f or co lor
kev board handl er 278 COLOR keyword 396
L aunch Pad app li ca ti on 298 - 304 Co lor palette
mo,·in g co ntrols dy nami ca ll y 166 - 167 defin ed 41 3
1110,·i ng controls using mouse eve nts 197. Sea rch Help f or Co lor palette
2 12 - 2 13 Co lor pa lette comm and Sea rch Help fo r Co lor palett e
numbers command
N umber Sys tem appli ca ti on 11 3 - 11 5. COM keyword 396
130 - 13 1 COM port s 3 15
pri me number. tes tin g fo r 245 - 246 Co mbo box control
pri ntin g numbers usin g loops 9 1 - 93 A ddl tem meth od 135
pa.)~ i ng argurnc1ll~ b) , aluc 97 Change eve nt 139
pr int ing tabl es 154 - 155 Cli ck event 139
Proj ec t Plann er appli ca ti on 106 - 107 Db!C lick event 139
Record Editor appl icati on 336 - 350 defin ed 134, 4 13
res tri cting keystrokes 128 drop-down li st box J 35, 139
Roc k ·11 · Rol! appli ca ti on 2 17 - 226 DropDow n event 139
Sc ribbl e appli ca ti on 199 - 20 1, 204 - 205 ge tting at con tents of li st 136 - 139
Te mpera ture Co nverte r 147 - 148 initi ali zin g 135- 136
Tex t Edit or appli catio n 320 - 33 1 Li st propert y 135, 136 - 137
Try M enu s appli ca ti on 109 - 112 Li stCount property 135, 136
See also Code exa mples (o nlin e Help) L istlndex propert y 135 , 136 - 137
,ide ma intenance mouse even ts 196
Sliifi and KnCode co nstant ~ i n globa l module 27:-l plac in g items in li st 135 - 136
type and co nstant de finiti ons 258 properti es. eve nt s. ancl meth ocl s ( li st) Search Help
,de me ,rn command~ for combo box
See specific cw11111011d 11wne.1 referri ng to items in li st 137
Seorch He/¡1for Code men u co mm and s Remove ltem meth od 136
,)de te mplate se lecti ng tex t in 264
defin ed 4 1. -+ 12 Se lLe ngth . Se lStart. Se !Tex t prope rt ies 264
di ~played 68. 70 Sort ecl propert y 135
·, ,de w i ncl o" Style propert y settings 134 - 135, 139
nea t,n g proced ures. short cu t 94 Tex t property 135, 136 - 137
de fin ed ..¡ 12 T oo lbox loca ti on 48
runn ing Help code exa mpl es fro m 29 - 30 types of 134 - 135
u~ in g 68 - 7 1 Comm a (.)
Seorch He/pfurCode w indow num ber fo rm ats 128
,Id li nk 356. 360, 370. 371 Pri nt method ancl 15 1. 154
Il ion ( :). scpara tin g argum ent s 8 1 se paratin g argum ent nam es 95
·11 lor Co mm ancl
argument. L in e me thod 18-+ See specific co111111a11d 11a111es
i111·ertin g, dragg in g co ntroh 2 11 Search Help fo r comm ands
i 11 ve rti ng. rec tangles 384 - 385 Co mm and button contro l
spec ify in g attac hin g code 42, 71 - 72
co nstant s 178 Capti on propert y 40, 102
hexadec ima l numbers 180 Cli ck eve nts, generatin g 102 - 103
PSct 18 1 Ctl ame propert y 64
QB Co lor run cti on 179 defau lt ca nce l butt on 102

'1/,crosoft Visual Basic Programmer's Guide


Contro l st ruc tures 42~

Co mm and button control (co111i11ued) Control (co111i11ued)


defined 49, 4 13 deletin g, cles ign time 54
Enabl ed prope11 y 107 - 108 dragging ancl clropp ing 207 - 2 13
prope11i es , events, and methods (l ist) Search Help drawi ng, des ign time 37 - 38 , 48 - 52
fo r comm and button enabling/di sablin g 107 - 108
pu sh butto n 49 fin din g control with foc us 266
setting capt ion with Properti es bar 40 hi ding/showing, V isibl e propert y 168- 169
Too l box locati on 48 max imum number on fo rm 170
use in shell app li cations 105 mov ing
V isible propert y 107 des ign ti me 53 - 54
Co mm and-line arguments dynam ica ll y 166 - 167
startin g Vi sual B as ic using 17 using mouse events 197 . 2 12 - 2 13
te sti ng 240 multiple (controls), manipu lating 54
Comm and $ fun cti on 240 passing to DLL routines 387
Com 111 and s remov ing, usi ng Un load statement 169 - 17 1
Sel! spl!t ijic command 11wi1es res izin g
Search f-lelp f or comm ands design time 53
Co 111 111 ent sy mbo l x v, 80, 4 13 run-ti me 168
COMMON SH A RED state111ents 394 selecting drag icon 208
Co m111un ica ti on icon s (!con Library) 40 1- 402 sett in g properti es via Properti es bar 58 - 64
Co mputer 1cons (!con Library) 402 - 403 shortcuts
ConfirmFi le Function procedure drawing 52
code 290 - 29 1 setting properti es 62
Record Editor app lica ti on 338 show ing/hidin g, V isib le propert y 168- 169
T ex t Editor appli ca ti on 322 testing for type 249 - 25 1
Con st statcment view i ng sett in gs in Properti es bar 58
dcc larin g sy mbol ic co nstant s 258-259 Search f-lelp f or control
G loba l keyword w ith 25 7 Co ntrol array
sy ntax 258 add i ng controls usin g 169 - 17 1
Co n'-! ant co 111pared w ith oth er arrays 252 - 253
dcc lari ng sy mboli c constant s 258 - 259 creatin g 170 - 17 1, 252 - 253
dcfi ned 8 1. 4 13 defi ned 11 6 - 11 7, 169 - 170 ,4 13
typographic conve nti ons for xv index argu111ent 169. 252 - 253. 368
CONSTA T.TXT li 111 itati ons 170, 25 3
co lor co nsta nts defined in 178. 180 maxi111um number o f elements 170
data forrnat s de fin ed in 267 referri ng to elements in 252
DDE constants de fin ed in 359 settin g l ndex propert y 169, 170
E T ER. L EA V E, OVER defi ned in 2 11 synt ax 11 7
key codes defin ed i n 276, 277 Search f-lelp fo r contro l array
MB_EXCL A JM defin ed in 288 Co ntrol data type
sy mbo li c constants defi ned in 258 - 259 dec larin g 248 - 249
TR UE/ FA LSE defined i n 108 testin g fo r type 249 - 25 1
Seorch Help f or CONST AN T. TXT Contro l stru ctu res
Co nt i nue comm ancl ( Run menu ) def ined 86, 4 13
use or 23 0. 23 1 Do loops 9 1- 92
Search He/pfor Co ntinu e co111mand exitin g 245 - 246
Co nt ro l For loops 92 - 93
addi ng. using L oad stat emcnt 169 - 17 1 l f.. Then 87 - 88
al igning to grid 54 - 55 11' .. T hen .. .Else 88 - 89
a11achin g code to 69 - 70 nested 244, 4 18
CLI St0lll (co ntro ls) 377 - 378 Sclcc t Case statcme1~ts 90 - 9 1
dcfin cd 6, 37 , 4 1J Sn 1rcli Helpfor co ntrol structure

Microsoft Visual Basic Programmer's Guide


430 Control type

C,intrr,I typc See Co ntrol dat a type C tl ame propert y (co nrinued)
1·, ,ntrr,I B ox propert y 2 18. 2 19 defined 38
1 ,n, cr,a tion ( DD E) See DD E conversation labels 63
1_ .in,cr -, io n lün ction s te xt bo xes 63
LCasdi 105 tim er con tro ls 269
StrS 75 C'TRL key
LCase$ 105, 127. 133 se lectin g multip le control s w ith 54
Val 7-l testin g for. keyboard hand lers 275 , 277 - 278
, ,n, eni ng tes ti ng for . mou se eve nt s 206
Cehi u'>/Fahrenheit 147 - I-l8 CTRL+BREAK. brea kin g execution 230
degree'>lrac.Ji ans 192 C'TRL+PAGE 1)0\VN. I mmed i ate window 238
lo\\ ercase/uppercase 105 . 127, 133 C urrency data type
,tanc..lard approac h for 148 defi ned 80. 83 - 84
lé.\t/ numbe rs 74 - 75 11 0 1 support ed by DLLs 382
ti me fo rm al ~ 270. 271. 272 random -acccss fi les 333
,\) rJ1 nate ': , tcI11 Current di recto r)
creating custom sca le 171 - 174 providing user se lec ti on 297
c.Jefined 17 1 See a/so Fi lel nfo dialog box: L aun ch Pad
ncgati ,·e num be rs and frac ti ons 172 appl ica ti on
re \e ttin g to defaul t 175 C urrent drive
Scale mcthod 174 providing user se lec tion 296. 297
,e lec ti ng sta nd ard sea le 174- 175 See o/so Fil el nfo dialog box: L aunc h Pad
,e tting 17 1- 175 app l ica ti on
, Hl rJinates. drawing 152. 153 Cu 1Tcnt statement 232, 413
'P: L"Olll 11Janc..l Cu rrentX propert y
crea ti ng fo r app l ications 265 - 266 fo rm or picture box 152
pro, 1J in g DDE capabi l iti es for appl ica ti ons Pri lller objec t 158
1(17 .1 68 ,pccifying pri ntin g locati on 152. 158
'11: u1m111and (Edi l rn enu ) TextHeight. Tex tWidth meth ods 153
cIe,I II11 g 1)1)[ linb with J56. 357 Currcnt''{ prnpert)
'il'lln i, 1/elfi.fárcopy comrna nd form or pi cture box 152
'I" Pen I l)ra" Mode sc ttin gJ 186 Pri nte r object 15 8
'P: hle h1nd ion proccdure \ pecifying printin g loca ti on 152. 158
h1 nar1 1cr\Íon 3S 1 - 352 Cu~tom co nt rol file~
c·llde. 1llr ra nd om -access fi les 334 - 335 c.Jcfined 377.413
u, ed In Reco rd Editor app li cat i on 337 loading 378
1 p1I11g Cut anc.J paste co mm ands
c· ,Kk e.\a rnpl c\ from Hclp 29 - 3 1 crcating 265 - 267
c11 11tru l, 52 sc lcct ing te xt fo r 26..i
t"1lc,. hinary 15 1 352 C ut co mm and (Ed il menu ) Seorch /-/elp /á r C ut
l I lc,. rand orn -acccss 334 - 335 command
graphi cs fro rn obJCCl to objec t 163 CV D keyword 396
graphic~ to/frorn Cl ip boa rd 162. 267 CVDMBF keyword 396
lL' \l to/from Clipboa rd 265 - 267 CV I ke ywo rd 396
'il't1r,-/1 / l e/¡1.for copy codc: co py co ntro ls CVS kcyword 396
" illllL"lion 19 1 CVSMBF ke) word 396
1 •uI11 cr. dcfincd 92

( IL';lli 11g Cu, tom App li cation, ... tutoría ! 20


'> l~LIN 1-. cywo rd 3% D
·l.'\;1me propcrt y ª"
D. \ torin g Do ubl c data type 84
c· 11rn 11rnnd hutt on 6-l Dashcs. DrawSty lc sc ttin g 185
crL';lling co ntrol array \ 253 Data. dcfi ned 3 16

·.1,crosoft Visual Basic Programmer's Guide


Debug object 43

Data fil e, defi ned 316 DDE (ca ntinued)


Data forma ts (C lipboard) 267 eve nts 362- 364
DATA keyword 396 hot vs. co ld 356
Data type in terruptin g 360
Contro l item 355 , 358, 368, 4 16
dec larin g 248- 249 limiting cli ents 363
tes tin g for 249 - 25 1 methods 369 - 372
Currency naming appli cation 355, 367 - 368
defined 80, 83 - 84 openin g 362, 363
not supported by DLLs 382 ove rview 354-356
random-access fi les 333 pok ing data 370
declaring 83 - 84 properties 358 - 36 1
default 83, 259 - 260 req uesting data 370
defi ned 82, 4 13 se ndin g co mm and s 37 1
DLLs and 38 1- 387 se11ing response to DDE 361
Doubl e 83 - 84 start in g oth er appli cations 369
Form 248 statements vs. Exce l and Word statemen ts 37 2
lnteger System topic 355, 369
declaring 83- 84 term in atin g 362, 363
DLLs and 386 topic
random-access records and 333 defined 355, 421
li st of types 83 LinkTopic property 358, 359, 360 - 36 1
Long 83 - 84, 386 updating co ld link 356, 360, 370, 37 1
Single 83 -84 updating hot link 356, 37 1
String Search Help far DDE
dec laring 83 DDE app li cation name
DLL routines ancl 382 - 383 , 385 defined 355. 4 1 1
type-declara ti on characters 83 na mes of Microsoft produ cts 355
Use r-clefin ed referrin g to 355 , 367 - 368
crea ting 260 - 26 1. 332 DDE conve rsati on
defined 257 cli ent 354
DLL routin es and 384 - 385 clefined 354, 4 13
Search Help far data type hot vs. co ld lin k 356
Da ta va lidati on it em 355, 358, 368. 416
restri ctin g keystrokes 126 - 128 se rver 354, 355
tex t boxes 125 - 126 top ic 355. 358, 36 1, 368
Date See a/so DDE (dy nam ic data exc hange)
fonnattin g 157 DDE error numbers 373
retri ev ing curren t date 1 12 DDE it em 355, 358, 368, 4 16
Date$ func ti on 112 DDE topic
DblClick even t defined 355 , 42 1
co mbo box 139 LinkTopi c propcrt y 358,359, 360 - 361
li stbox 137 - 138 DDEExecu te (Word statement ) 372
DDE (clynam ic data exc hange) DDE lniti ate (Word stat ement) 372
app li cati on nam es. Microsoft prod ucts 355 DDEPoke (Word stateme nt ) 372
CF_LI NK 267 DDER equ est (Word state ment ) 372
creatin g DDE capabil iti es for users 365 - 368 DDETerminat e (Worcl state ment ) 372
creatin g link s at desig n time 356 - 357 Debug object
crea tin g link s wi th Exce l 359 - 360, 370. 372 defin ed 4 13
defin ed 354 - 356 . ..i 13 printin g to lmm ed iate wincl ow 235
error handlin g 363. 364. 372 - 375 Seorch /-/e/¡1/i>r Dchug obj ec t
errors due to respo nse ti me 360

Microsoft Visual Basic Programmer's Gu,de


432 Debuggi ng

D::'b ugging DEF FN key\\'o rcl 396


approac hes to 228 - 229 DEF SEG kcy,,ord 396
brcaki ng execution 229 - 23? Defau lt dat a type
dcfin ed 73,4 14 specifyin g 83 , 259 - 260
~pccia l considerations 239 Search Help far define type
testing Default settings . defined 38, 58. 4 14
co mmand -linc argumenl s 240 DefCur statement 259
da ta and procedures 235 - 239 De rDbl statement 259
traci ng executi on 233 - 235 Defl nt statement 259
usin g Jmm ediate window 235 - 239 Detl.n g statement 259
Search Help .fordebu gg in g Dc fSng state men t 259
Dec im al numbers (base 10) De fStr statemen t 259
defi necl 80 De fnpe stat ement
s,,itchin g to l l • - 11 5. 130 - 13 1 adapting from other Basic cocle 397
D::'c laration in global mod ule 257
Jcf1ncd ..i 1..i , pcc if°:)ing clefa ult data typc 83. 259 - 260
Search Help .for cleclaration Sea rch Help.fardefine type
Decla rations secti on Dclcte comm and (Edit menu )
clefined 4 14 use of 54
ecliting 85 Seorch Help far Delete commancl
Sea rch Help fór Dec larations secti on Delct in g
Dec lare statement cont ro ls 5..i
adaptin g from othe r Bas ic cocle 393. 397 files . tips ••
Ali a~ keywo rd 38 1 pictures 162
As ..'.\ ny keyword 38 1. 385 Seorch Help far delete cocle: del ete con trol s
By\la l key worcl 380 - 382. 386 Dc\ ign time. defi ned 37 , 229, 41 •
clec larin g DLL routin es 379. 380 - 381. 38:'i. 3Xh De ~ign-tim e error See Errors
Lih kcy,, ord .l 80 De,t in ati on . pixel 187
Dec laring DC\' ice Co nt e.xts. handles 386
arra,, or, ar i;1hlc, 253 - 256 ÍJL'' ice una, ai Jab le error mcssagc 280. 281
Contro l data typc 2• 8 - 249 í)i alog hox
Curre ncy data typc 83 - 84 custom cli alog boxes 2 17. 2 18 - 2 19
dcfau ll type 83 . 259 - 260 propcn ies 2 18-2 19
DLL rou tin cs 379 - 38 1 , impl e dialog boxe s
Dou hl c data type 83 - 84 crca ting wi th Jnpu tBoxS function
d) na mi c arra y~ 255- 256 1• 3 - 1• 4, 2 19
fix ed- le ngth strin g\ 25 1 creatin g with Msg Box stateme nt 146,2 19
r·orm dat a type 2• 8 Dig ital Cl ock appl ication 270 - 27 1
g loba! co nstanh. , ariables 25 3, 25 7 - 258 DIM SHARED statements. adapt in g 394
hand les in DLL rou tin es 386 Dim state men t
lntegc r el ata type 83 - 84, 386 aclapting from oth er Bas ic cocle 394 . 396, 397
Lon g dat a type 83 - 84. 386 declarin g
mu lticlim ensional arrays 255 a rra ys of vari ab le<, 253 - 25 6
Single data tvpe 83 - 84 dynami c arra ys 25 6. 397
, tatic va riabl e, 2• 7 fi xed arrays 253
String data type 83. 382 - 383 1·ixed-length strin gs 25 1
sy mbo li c co nstanh 258 - 259 rnulticlime nsional array s 255
two-dim e nsional arrn ys 225 ,·ariabl es 83 - 86
usc r-de lin ecl type 260 - 26 1. 332 pl;1cement 84 - 86
See u/so Scopc scopc 84 - 86
í)I T f.N fun ct ion 39 .1 S1a1ic ~c,·1, orcl a ncl 247

Microso ft Visual Basic Programmer's Guide


Drawi ng 433

Directory li st box control DOS


Change eve nt 299 ru nni ng Setu p from 16
defi ned 4 14 starting Vi sual Basic from 17, 36
Laun ch Pad appl icati on 298 - 304 Dots, DrawStyle settin g 185
mou se events recog ni zed 196 Doubl e data type, decl arin g 83 - 84
Path propert y 297 Drag method
properti es. eve nt s, and meth ods (li st ) Sea rch Help defined 207
for directory li st box use of 2 11
Toolbox location 48 Drag-and-drop operati ons
Vi sibl e property 3 14 caus ing control movement 207, 2 12 - 2 13
working with 297 co ntrolling start/stop 2 11
Di sk not ready error message 28 1 defined 207,4 14
Di visio n Drag method 207 , 2 11
error-hand li ng rout ine for 28-1 - 285 DragDrop event 207, 209 - 2 1O, 2 13
int ege r di vision vs. modul o arithmeti c 99 Draglcon property 207. 208. 2 1O
operato rs 98 DragMode property 207, 208, 2 11
trun ca ti on vs. round in g 99 Dragüver event 207, 21O- 2 11
DLL (dy nami c-li nk li brary) routines hi ghli ghtin g objects 2 10 - 2 11
ca lling with spec ific elata types mu lti ple-form operati ons 207 , 2 12
arrays 383 overview 207
fo rm s and co ntro ls 387 responding to drop eve nt 209 - 2 1O
handles 386 se lecting drag icon 208
null pointers 385 DragDrop event
prope ni es 386 - 387 argu ments 209
stri ngs 382 - 383 defin ed 207
user-defined type s 384 - 385 use of 209 - 2 1O, 2 13
clec larin g Dragg ing
non sta ncl arcl names 38 1 defin ed 207
pa ss in g arguments 380 - 38 1 See also Drag-a nd-drop operati ons
, pcc ilyin g library 380 Draglcon property
Suh vs . Fu ncti on procedure 379 assignin g drag icon 208
usin g fl exib le argument types 38 1 chan ging when over target 2 1O
cle li necl 377 . 4 14 defined 207
lihn ame clause 380 DragMode property
Do loop automatic 208, 2 1 1
compared wi th For Loop 92 defi ned 207
co ntrol structure 86. 9 1- 92 manu al 2 11
Do Whil e vs. Whil e ... Wencl 91. 245 Dragüver eve nt
Do Until vs. Do Whil e Not 92 argumen ts 2 1O
exitin g 245 defi ned 207
Do Unti l 92 useof210 - 2 11
Do Whil e 91 DRAW 396
Do Whil e Not 92 Drawin g
Docum entation set ares 19 1 - 194
organi zation 10 - 12 BackColor property 177. 18 1
typograp hi c conventions used in xiii - xv boxes 188 - 189
DoEvents fun cti on circl es 186, 189 - 190
crca tin g idl e loop with 273 - 275 clearing 180 - 18 1
DDE ope rati ons ancl 374 -375 co ntrol s 37 - 38, 48 - 52
Doll ar sign ($ ) sy mbol DrawMode propert y 177 , 186 - 187
form att ing num eric outpu t 156 DrawS tyle propert y 177, 185
Stri ng type-de claration charac ter 83 DrawW idth property 177, 184

Micro soft Visual Basic Programmer's Guide


434 Drawin g

l)rawi ng lcontinued) Editin g Sea rch H elp.foredit code ; ed il cap ti on: edit
ellip~es 190 - 19 1 men u bar; undo
ForeColorpropert y 177. 18 1. 184 E llipses, drawing 190 - 191
fundamenta l co ncepts 175 - 18 1 Else clause
lin e~ 182 - 188 use of 88, 250
point s 181. 187 See also lf.. .Then ... Else statement
po lygo ns 183 Elself clau se
rectang les 384 - 385 use of 88, 249 - 250
spoked pattern 183 See also Jf...Then ... E lse statement
Search Help .fordraw E lself...T ypeOf statement 249 - 250
DrawM ode propert y Enab led property
defi ned 177 Boolean sett i ngs 107
se ttin gs 186 - 187 chec king statu s of control 108
DrawStyle property defined 4 14
defin ed 177 defaul t se ttin g 58
~elli ng~ 185 enabl in g/disabling co ntrol s 107
Dra wWidt h propert y menus 11 3
defin ed 177 tex tboxes 147
specifying width of line 18-+ Timer control s 269
Dri ve Iist box con trol End command (Run menu) 42, 73. 229
Change eve nt 299 End I f statement, 87. 244
defi ned 4 14 END key, use in Immedi ate wi ndow 23 8
Dri\ e property 296. 297 End -of- line See Newline character
Fi leln fo dialog box 305 - 31 -+ End statemen t 226
Launch Pad app li ca tion ?.98 - 304 End Sub 67
mouse eve nt s rccog nized 196 En dDoc method 159
properties. event~. and methods ( li~t ) Search He/p ENTER key
/111· dri\e li~t bo\ ASC II number 127
Toolbox locat ion 48 keyboard handlers and 275
Vi,irilc propcrt> .1 l-+ use in lmmediate window 238
workin g with 2%. 297 EOF function
Drwe property. dri\·e li st box ?.96, 297 file access 316. 326
Drop-do wn li st box Input$ statement and 398
crea cin g 135 Eq ual sign (=)
C\ ents 139 ass ignment statements 8 1
DropDo\,·n eve nt. cornho box 139 Co nst statement 258
Dro ppin g opera tor 88, 98
defined ?.07 Eqv operator 88, 98
See o/so Drag -and -clrop operations ERDEV keyword 396
D~ namic ;irrays 255 - 25 6. 397 ERDE Y $ ke yword 396
D\ namic Data Exchange (DD E) See DDE (dynamic Err function
data exc hange ) defi ned 28 1, 283
Dy namic -link l ibra ry (DL L ) See DLL (uynam ic-link de layed error-handling examp le 29?. ?.93
li braryl routinc s use wi th Error 287
Error codcs
DDE error numbers 373
retri ev i ng wit h Err 28 1, 283 , 292 - 293
1·.d it co nt ro l See Tc.xl box contro l Seo rch He/p .for trappabl e errors
Ld it field See Tcxt hox control Error Err stateme nt
Ld it menu co mm and s defin ed 283
See specific cn111111mul nmn e 1 w hen to use 288
Seorch He/p jin· Edil mcnu co rnmancls

Mic ros oft Visua l Basic Progra mmer's Guide


Exiting 435

Error handling Eve nt proced ure (co111i11ued)


active trap 282, 286 tips on writing 67-68, 130
Basic languages compared 395 writing first event procedure 40-43
centrali zi ng error handling 288-292 Sea rch He fp for event procedures
CheckTxtFiles Sub procedure 280-28 1 Eve nt-dri ven app li cation 4, 4 14
ConfirmFile Function procedure 290- 292, Event-driven programmin g 4 - 5, 7 - 8, 414
322,337 Eventn ame
DDE error routines 363. 364, 372 - 375 defined 4 1
DDE time-out error 360 naming even t procedures 7, 4 1, 67 - 68
delayed 292 - 293, 304 Eve nts
Dividelt Function procedure 285 defin ed 4, 4 14
enabling trap 282, 286 li st of Search Hefp fo r eve nts
ex iting error-handling routines 283 - 286 Exa mpl e code ( Programmer's Cuide) See Code
Fi leErrors Functi on procedure 288-290, 322,337 exa mpl es ( Program111er's Cuide)
guidelines 282 - 283, 288 Exa mple code (online Help)
invocati on path 283, 286 copyin g and runnin g 29 - 31
LinkError event 363, 364. 373 Search Help far code exampl es
need for 280 Exclamati on point ( 1), Single type-dec larati on
ove rview 282 -286 character 83
placement of routine 282 Exclúsive Or (Xor) 88, 98
resuming execution 283 - 285 .EXE file
retrieving error code 28 1. 283, 292- 293 creating 76
retri eving error message 28 1 picture fil es in 163
rout ine for di sk 1/0 288 - 292 Search Help for make executable
Text Ed itor applicati on 322. 325 Executab le code, clefined 415
turnin g off 293 - 294 Exec utabl e fil e
un anti cipated errors 286 - 288 creat in g 76
Veri fyFi le Function procedure 285 - 286 defin ed 4 15
Search Helpfor error handling run ning 76
Error messages Sea rch He fp for cxec utabl e fil e
returnin g with En-or$ 281 Exec ut able stat ement. defin ed 4 15
Search Help fo r trappable error~ EXECUTE (Exce l statement ) 372
Erro r statement 286, 287 Executing code
Error trap halti ng at probl em state ments 230- 233
enablin g 282, 286 procedure steppi ng 234
See a/so Error handlin g setting nex t stateme nt 234 - 235
Error trapping sin gle steppin g 233 - 234
defin ed 4 14 Start comm and (Run menu ) 73, 229
See a/so Error handling testing comm and-line argum ents 240
Error. function 28 1 testing data and proced ures 235-2 39
Errors using lmmediate window 235-239
DD E time-out 360 Sea rch Help forexec ute code
log ic errors 228, 4 17 Ex it co mmand (File menu ) Sea rch Hefp for Exi t
run -tim e errors 228,420 comm and
syn tax errors 228, 421 Exi t Do 245
Search Help forre so lve errors: trappabl e errors Exi t For 245 - 246
Eve nt See Events Ex it Functi on statement 246
Evc nt procedure Ex ir stateme nt 246
as Sub procedure 94 Ex it Sub statement 246
defin ed 7, 93, 4 14 Ex iting
namin g 7, 4 1. 67 - 68 multipl e-form app lica tions 226
~y nt ax 67 Set up program 16

Microsoft Visual Basic Programmer's Guide


436 Exiting

Ex itin g (co ntinu ed) Fil e li st box co ntrol (con tinued)


Vi ~ual Bas ic 43 Path propert y 297, 3 1 1, 3 14
Sea rch Help fo r ex it Pattern propert y 297, 3 14
Expone nti ati on (") 75. 99 properti es, events, and methods (li st) Search Help
Ex pre<,s ion, defin ed 4 15 fo r fil e li st box
Too lbox locati on 48
r- Vi sible property 3 14
workin g with 297 ,3 14
F opti on, Line method 189 See a/so Fi lelnfo di alog box; L aunch Pad
FI ke) (H elp) applica ti on
contex t-sensiti ve Help 25 Fil e menu commands
icon in doc um entati on I O See specific command names
staning Help 24 Sea rch Help fo r fil e menu comm ands
F5 key (Start co mm and ) 42 Fil e number, retrievin g 3 16, 3 18
F~ (S ing le Step command) 233 File+ Open dialog box (Fil eln fo dialog hox)
~':I key (T ogg le Brea kpoin t com mand J 231 cocle 306 - 3 14
Fahrenheit/Ce lsiu s, conven in g 147 - 148 propeni es 305
Fa lse Tex t Editor appli ca tion 328
defi nin g 108, 258 Fil e pointer, positi oning w ith Seek 352
integer for 108 Fil e-system control s
use w ith Boo lean propenies 99 Fi leln fo di alog box 305 - 3 14
Field See Tex t box control L aunch Pad application 298 - 304
FI ELD keyword 396 Toolbox loca tion s 48, 296
Field s. random -access f il es 331. 333. 340 working with 296 - 297 , 3 14
Fil e See File. proj ect: Fil e. system Sea rch Help fo r fil e system controls
Fi le. projec t Fil eE,,-ors Functi on procedure
clele tin g 44 code 288 - 290
renarn in g 4-1 Record Edi tor appli cati on 338
sharin g/s torin g -1-1 T ex t Editor applica tion 322
types or ,.n File l nfo dialog box
Fi le. sys te m code 306 - 3 14
di splay ing. u~i ng fil e ~ystem control ~ properti es 305
296 - 297. 3 14 Tex t Editor appli ca tion 328
Fil el nfo di alog box 305 - 3 1-1 Fi leüpener Fun cti on procedure 3 18 - 320
Launc h Pacl app lica tion 29 , - 30-1 FILES keyword 396
Seorch Help./iir fil e-sys tem contro ls Fill Sty le propert y 188
Fi le acces<, Find co mmand (Code menu) Seorch Help for Fin d
bi na ry 3 16 - 3 18. 350 - 35:2 comm and ; pattern matching
binary vs . rand om 350 -35 1 Fi nd Nex t comm and (Code menu ) Sea rch Help for
opcn in g fil e. spec ifyi ng mode 3 17, 3 18 - 320 Find Nex t co mmancl
ra ndom 3 16 - 3 18, 33 1- 350 Find Prev ious co mm and (Code menu ) Seorch Help fo r
ra ndom V', . '>eyu ent ia l 331 Find Prev ious command
scq uenti al 3 16 - 3 18. 320 - 329 Findi ng code Sea rch Help for find code
type s o f 3 16 3 17 Flag ico ns (]co n Library) 403
1-i lc in pu1/ou1 pu 1 Floa ting- point numbers 84
hi nary 3 16 - 3 18. 350 - 35:2 Foc us
random access 3 16 - 3 18. 33 1- 350 A ctiveControl propert y 266
sequ enti al acce~\ 3 16 - 3 18. 320 - 329 defin ed 102, 4 15
l 'ilc li st box co nt ro l key board events and 276
a11 ribu1 c pro pcrti e~ 31-1 Fo nt properti es 149 - 150
dcfincd 4 15 Fo ntB old propert y 149 - 150
111 ouse eve nt s rccog ni 1.ed 196 Fon tlta l ic propert y 149 - 150

Mic rosoft Visual Basic Programmer's Gu,de


Function procedure 43

FontN ame propert y 149 - 150 Form (continued )


Fonts Width property 64, 168
proporti onal 154 Search Help for fo rm ; stai1up fo rm
setti ng characteri stics 149 - 150 Form code, defined 4 15
FontSi ze propert y 149 - 150 Form data type 248
FontStri kethru propert y 149 - 150 Form window Sea rch H elp fo r Form window
FontTransparent propert y 150 Form-level vari able 85 , 4 15
FontU nderline property 149 - 150 Form_Load event procedure
For loop initializing va lues 125, 222, 226
compared w ith Do Loop 92 Record Editor appli cati on 339 - 340
cont ro l structure 86, 92 - 93 , 244 Text Editor appli cati on 325
counter 92 Format$ fun ction
ex iting 245 formattin g dates and ti mes 157
sy nt ax 92 formattin g numbers 75 , 156 - 157
Fo r .. .Nex t stateme nts 92 - 93, 244 sy ntax 156
ForeColor propert y Formatting
defin ed 142 dates and tim e 157
Lin e method 184 numbers 75, 128, l 56 - 157
PSet method 18 1 output direct to printer 158 - 159
use with graphi cs 177 , 18 1, 184 output to fo rm or picture box
Form combining items o n line 151- 152
attac hin g code to 69 - 70 printing at spec ific location 152
A utoRedraw pro pert y 159, 176 TextHeight , TextW idth methods 153
Capti on pro perty 63 tabular data 154 - 155
creating new form 37 Formul as, interest co mpounded dail y 75
defin ed 6, 37,4 15 Frame control
DDE server 354, 355 defin ed 4 15
DLL routines and 387 drawin g 299
Height propert y 64. 168 properti es , event s, and meth ods (li st) Search He/¡ 1
lco n propert y 22 1 f or frame
mouse eve nts recog nized 196 Toolbox locati o n 48
multipl e-form app licati ons FRE keyword 396
di alog boxes 217. 2 18 - 219 FreeFile fun cti on 3 16, 3 18
drag-and-drop operati ons 207, 2 12 .FRM fi le 44
ex iting 226 Functi on keys
genera l-purpose for ms 2 16 - 218 ass igning to menu com mands 120
Hide meth od 216, 224-225 keycodes fo r 277
hiding fo rms 224- 225 Visual B as ic fun cti on keys
Load statement 2 16, 225 - 226 F I (He lp) 24, 25
loading and d ispl ay in g 222 - 224 F5 (S tart comm and) 42
loading witho ut displ ay ing 225 - 226 F8 (S ing le Ste p command) 233
modal 222 F9 (Toggle Breakpoi nt command ) 23 1
se lec ting icon for 22 1 SHI FT+F8 (Procedure Step comm and) 234
Show method 216, 222 - 224 Search Help for shortcuts
start up fo rm or mod ul e 220 - 22 l Functi on proced ure
sy ntax 2 16 calls to 80, 94, 96 - 97
Unl oad state men t 2 16, 226 compared with S ub proced ure 94, 96
pictures, adding and di spl ay in g 162 - 165 creating 93 - 94, 96 - 97
printing to 15 1- l 53 defin ed 4 15
res izin g dynami call y 168 DLL routines and 379
settin g properti es first exa mpl e 58 - 64 ex itin g 246
view ing p rope rt y settings 58 pare ntheses in 80, 96, 396

Microsoft Visual Basic Programmer 's Guide


438 Function procedure

Fcnc ti on procedure (cont inued) Graphics ( continued)


,cope of 94 drawing (continued)
,y nt ax 96 polygon 183
typogra phic conven tions xv rectangles 384 - 385
Search He/p far Function procedure spoked pattern l 83
fund amentals of 175 - 18 1
DrawMode property 177, 186 - 187
DrawStyle property 177, 185
Gé'nera l procedure DrawWidth property 177. 184
creating 94 ForeColor property 177, 18 1. 184
de fin ed 43. 4 15 graphi cs methods, li sted 177
editin g 94 graphics properties, li sted 177
when to use 93 - 94 persistent graphics 176. 4 18
Search Helpfor ge nera l procedures See a/so Icon
Gel statemen l Sea rch He!p for graphi cs; icon
bi naf)' fil es 350 - 35 1 Greater than (>) operator 87 - 88. 98
ra ndom-access fil es 3 16, 334 - 335, 340 Greater than or equal to (>=) operator 87 - 88, 98
Record Ed itor appli cati on 340 Grid
Gct Data method 267 aligning control s to 54 - 55
G.:t Format method 267 changing sett ings 55
G.:cTex t method 265 - 266 defined 54,4 16
Global. defined 4 15 Search Help jor grid
Globa l keyword Grid Settings command (Edit menu )
dec lari ng arrays 253 - 254. 256 use of 55
use with Const 257 - 258 Search Help for Grid Sett in gs com mand
use in place of Di m 83, 257 GUI (Graphi cal User Interface) 4. 6
(j ,bal modu le GW-BASIC language
arrays of variab les clefined in 253 adaptin g code from 39 1- 398
creating 257 BAS ICA and 39 1
de fi ned 37.43. 257.4 15 compared with Visu al Ba~ic R - 9. 392. 394
Rcrn rJ Editor application 33~
runnin g Help code examp les using 3 1
,y nt ax used in 257 H
Tex t Ed itor appl icati on 323 Handle 386. 416
1·ariab lcs, constan ts, and type in fo rm at ion in 257 hDC property 386
Search Help for globa l module Headers, printing 159
Gl1Jbal va riable 85 , 257 Height property
G, 1Su h statement , adapting from other Basic code 393 resizing con trols dynamicall y 168
Grc1 phica l User Interface (GU I) 4, 6 settin g via Properties bar 64
Gra ph ics vs. ScaleHeight 172
add in g pictures to forms 162 - 165 Heli o, world 1 appli cati on
BackColor property 177 , 181 code 4 1- 42
clea rin g drawing area 180 - 181 controls and properties 37 - 40
coordin ate systems 171 - 175 Help
copy in g to/from ClipboarJ 267 context-sens iti ve Help 25
draw in g copyi ng/ru nning He lp code exa mples 29 - 3 1
ares 19 1 - 194 FI key access IO, 24, 25
boxes 188 - 189 jumps 27, 416
circles 186, 189 - 190 Search command IO, 24, 26 - 27
elli pses 190 - 19 1 Setup program help 16
lin es 182 - 188 starti ng 24
points 18 1, 187 Search Helpforcode examples

Microsoft Visual Basic Programmer's Guide


lmp operator 439

Help me nu commands lcon ( con linu ed)


See specific command names fi le ex te nsio n 162,22 1
Search Help for Help menu co mmands !con Library li sting 164, 399 - 409
Hex$ fun ction 11 4, 13 1 !con property, form s 22 1
Hexadecimal numbers (base 16) sources 164
defined 80 Search Help for icon ; M ake EXE Fil e dialog box
setting colors with 180 !con Library
Number System app lication 114 - 11 5, arrows and pointers 400-40 I
130 - 13 1 co mmun icatio n icons 401 - 402
Hidde n property , fi le li st box 3 14 co mputer icons 402 - 403
Hide method described 164, 399
forms 224- 225 íl ags 403
defined 2 16 mail icons 404
Visible property a nd 225 mi scell aneous icons 404 - 406
sy ntax 2 16, 224 offi ce icons 406 - 407
vs. unloading forro s ·226 tra ffic signs 408
Hierarchical me nus writing icons 408 - 409
defined 109,4 16 Sea rch Help for !con Library
See also Menu contro l !con property, form s 22 1
HOME key, use in Immed iate window 238 !con Works application 9
Horizontal scroll bar control !die application 375
adding to Record Editor 349 - 350 !die loop
Change event l 4 l , 142 c reating with DoEvents 273 - 275
defined 4 16 defined 4 16
getting user input 140 - I 43 DoEven ts and DDE operati o ns 374 - 375
LargeChange propert y 14 1 whe n to use 273
Max prope rt y 14 1 Id le time 273
Min property 141 lf...Then state ment
properti es, eve nts. and meth od s ( li st) Search He/p cont rol structure 86, 87 - 88
fo r scro ll bar nested 244
se ttin g co lo r with . e., amplc 1-1 :2 - 1-11 ~y ntax 87
S mall Change property 14 1 If. .. T he n ...E lse state mé nt
Toolbox locati o n 48 compared with Select Case 90
Va lue property 14 1 co ntrol stru cture 86, 88 - 89
Hot lin k Elself clause 88
creating 356 - 357 , 359 nested 244
defined 356, 4 16 use in error-handling routines 282
enabling users to create 365 - 369 If. ..Typeüf state me nt 249 - 25 0
exampl e, with Exce l 359 lmmed iate window
updating 356, 371 defined 73,4 16
hWnd property 386 opening 236
Hyphe n (- ), c reating menu -sepa rator bar 111, 117 printin g from within 236 - 237
printin g to 235 - 236
running Help code exa mpl es from 30
sho rtcu t keys used in 238 - 239
.ICO fil e 162, 22 1 tes ti ng data and procedures in 235 - 239
!co n ti ps on use of 238 - 239
ass igning drag ico n 208 title bar 237
creating animati o n effects with icons 165 whe n to use 230, 235
c ustom ico ns fo r form s 22 1 Search Help for lmmed iate window
de fin ed 4 16 lmm ecli ate wi ndow comm and (Window me nu ) 23 6
Imp o perator 88, 98

Microsoft Visual Basic Programmer's Guide


440 lmpl ication

Impli catio n (lmp) 88, 98 ·· 1ntrod uci ng Visual Basic," tutorial 20


lmporting code ln va lid filename , error message 279
adapting other Bas ic code 392-398 lnvestment Calculator application
Load Text com mand (Code menu ) 392 advanced features 89, 97
Search He/p Jor impon code code 66 - 75
1nclusi ve Or (Or) 88, 98 controls and properties 49 - 52, 61 - 64
lnJex, defined 4 16 ln vocation path
lndex codes, random-access file s 340 defined 283, 416
lndex property trac ing 286
creating control arrays 116. 169, 170, 253 IOCTL keyword 396
error if index number in use 171 IOCTL$ keyword 396
Timer control s 269 ltalic , font fonnat 150
lnitia li za tion lte m (DDE) See DDE item
dcfin ed 416
Form_Load event procedure 125, 222, 226
Load statement 226 J
properti es 222, 226 Jumps, in Help 27 , 416
Show method 222
Timer control 269
variab le s 125 K
I'.'\TTIA TE (Excel statement ) 372 Key codes 277
l'.\'KEY state ment, using Key Press even ts in stcad 395. KEY keyword 396
396 KeyAscii argument 127 - 128
l'.'\KEYS ke y word 396 Keyboard hand ler
1:\P keyword 396 access and shortcut keys compared wi th 275
1np ut mode , Open statement 317 . 3 18, 320 ge nera l, example 278
l:\PUT # statcmc nt. ada ptin g to Vi sua l Basic 3 16. 3 17. KeyCode arg ument 276, 277 , 278
395 Key Down , KeyUp, and KeyPress compared
lnpu tS statemcnt 275-276
acl apting to Vi~ual Basic 398 \º1,i(I a rgumcnt 277 - 278
ll'.'-11... •· 1tl1 11IL l) P"-',', _) 1(> writing, fo r KeyDown and KeyUp 275 - 27i:,
lnputBoxS fun cti on Kcyboard shortcuts
c reatin g dialog boxes 143- 144, 219 creatin g for users 120 - 12 1
prompt i ng u~e r, exa mpl e l 18 CTRL+BREAK (breaking execution ) 230
sy nt ax 143 FI key (He lp) 24, 25
whe n to use 143 F5 key (S tart command , Run menu ) 42
lnse rtin g text (cu t-and -pas te com mands) 26--1. F8 key (Sing le Step command , Run me nu) 233
~65 - 266 F9 key (Togg le Breakpoint command , Run menu)
ln se rti o n point 23 1
defined 4 16 lmmedi ate window keys 238 - 239
pastin g tex t at 264 SH1Ff+F8 (Procedure Step comm and . Run menu )
lnSt r fun cti o n 128 234
1ntege r data typc Vi sual Bas ic shortcut ke ys Search Help/ár
described 83 - 84 sho rtc ut s
DLLs a nd 386 KevCode argume nt 276, 277
Lon g 83 - 84. 386 Key Down event
ra ndo m-access reco rds and 333 breaking execution durin g 239
lntcge r di vision 99 c haracters detected by 127 , 275 - 276
Interfa ce. Vi sual Basic KevCode argument 276, 277
parts o f 6 Key Press compared with 126, 275 - 276
Se(lrch He /p for interfa ce Shift arg um ent 276, 277- 278
lntc rva l propert y, timcr 268,269 writing keyboard handler for 276 - 278

Microsoft Visual Basic Programmer's Guide


Link 44

Key pad keys , codes in CONST ANT.TXT 277 Len


KeyPress event clause with Open statement 318, 3 19, 334, 340
KeyDown and KeyUp compared with 126, ignored in bin ary access 320
275-276 Less than ( <) operator, 87 - 88, 98
keys detected/undetected by 126, 275 - 276 Less than or equ al to (<=) operato r, 87 - 88, 98
steps in writing procedures 127 Lib keyworcl 380
translating and restricting keystrokes usin g Library See DLL (dynami c-link library) routines
126 - 128, 133 Line
Keystrokes drawing, graphi cs methods 182 - 188
sending to other applications 375 -37 6 drawing, in res ponse to mouse events 198 -206
translating and restricting 126 - 128, 133 DrawMocle property 186 - 187
KeyU p event DrawStyle property 184, 185
cha racters detected by 127, 275-276 DrawWidth property 185
KeyCode argument 276, 277 See a/so Line methocl
KeyPress compared with 126, 275 - 276 Search Help fo r dra w lin e
Shift argument 276, 277 -278 Line breaks
writing keyboard handler for 276-278 converting fi"I es with nonstandard characters
Key word 330 -33 1
de fined 416 tex t boxes 124
search Help using 10, 24, 26- 27 Text Ed itor appli cati o n 326, 328
typographic conventions xv TextHeight method and 153
unsupported keywords (list) 396 - 397 See also New line character
Vi sual Basic keywords (list) Search Help Jor Line Input # statement
language adapting from other Bas ic code 395
checkin g encl-of-line charac ters 330 - 33 1
readin g fi les lin e by line 320, 326 - 328
L Line labe l
Labe l contro l in cocle examp les x v
BorclerSty le prope11y 147 GoSub, GoTo state me nts 393
C1p1in11 prn11cr1, ó3. 1..r., O n f:rrn r c;,,T<> ,1:11l'lllc'llh 282. >98
CtlN ame property 63 Resume li ne state me nts 283 , 285, 286
DDE cli ent 354 Line methocl
defined 49 , 417 B option 188
di splay ing ou tput using 147-148 desc ribed 177
mouse even ts recogni zecl 196 clrawing
properties, events, ancl methods (li st) Sea rch Help boxes 188 - 188
for !abe! lines 182 - 188
Too lbox location 48 polygons 183
Label, line See Line ]abe] spoked pattem 183
Language Reference I O F opti on 189
La rgeChange property, scroll bar 141 specify ing coordina tes 182, 187 - 188
La un ch Pad application Step keyword 187 - 188
code 299- 304 sy ntax 182
interface 299 use with mouse events 198, 199-206
properties 298 Line-co ntinuati on charac te r, in code examples x i ii , x vi
LCase$ fun c tion l 05 Linefeed characte r See New line character
Leacl ing spaces, trimming 11 5, 13 1 Link
Le ft property acknowl edg ing 364
defi necl 166 c lie nt link, defined 356
rnovin g controls clynamically 166 - 167 creati ng at des ign time 356-357
settin g v ia Properti es bar 64 defi ned 4 17
events 362 - 364

Microsoft Visual Basic Pro grammer's Guide


442 Link

Link ( con rinued) List box co ntrol ( con tinued)


hot vs. co ld 356 initia li zing 135- 136, 138
interruptin g 360 List property 136, 137
methods 369 -372 L istCount property 136
open ing 362, 363 Li stlndex property 136, 137
properti es 358- 36 1 mouse events recogni zed 196
server link, defined 357, 420 placing items in list 135 - 136
terminating 362, 363 properties, events, and methods (list) Search Help
types of 356 far li st box
upd a tin g referrin g to item in 137
co ld links 356, 360, 370. 371 Re moveltem method 136
hot links 356, 37 1 Sorted property 135
picture boxes 37 1 Text property 136, 137
See a/so DDE (dynamic daia exc hange) tips on writing events for 137
Search Help fa r lin k Toolbox location 48
LinkC lose eve nt working with user in put l 34 - 139
clien t links 362 List prope rty
serve r links 363 com bo boxes 136, 137
LinkErro r even t li st boxes 136, 1.37
client links 363, 373 ListCount property
server li nks 364, 374 com bo boxes 136
LinkExec ute event 364 list boxes 136
LinkExec ute method Listlndex property
comparab le Excel and Word statements 372 combo boxes 136, 137
se nding commands to applications 37 1 li st boxes 136, 137
Linklte m propert y 355, 358 Load event 125
LinkMode prope rt y Load statement
c li e nt lin ks 359-360 control s 169 - 17 1
com parabl e Excel and Word statements 372 forms 216, 225 - 226
~er"er link , v ; 1 mcnu co mman cb 1 1<:?
i.111 k. ÜJJC:ll C: I C lll !>yntax 216
c li e nt links 362 Load Text command (Cocle menu)
se rver lin ks 363 use of 392
Li nkPoke me th od Search Help for Load Text commancl
comparab le Exce l a nd Word statements 372 Loading fo rms
DoEve nts and 374 - 375 Load statement 2 16, 225 - 226
use of 370 Record E ditor application 339 - 340
LinkReq ues t me thod S how method 2 16, 222 - 224
co mparab le Excc l a nd Word sta te me nts 372 Tex t Ed ito r app li cati o n 325
upcla tin g co le! lin ks 360, 370 Search Help for load form
LinkSe ncl mcthocl 37 1 Loading pictures
LinkTimeO ut property 360 at run time 163
LinkTopic property Search Help fo r display graphic
c li e nt lin ks 358, 359 LoadPi cture function
se rv e r lin ks 355, 360 - 36 1 ass ign ing drag icon 208
List box co ntrol loading pictures at run time 163
Aclcl lt em me th od 135 - 136 Loe function 352
Click eve nt 137 - 139 Loca l variable
DblCli c k eve nt 137 - 139 creat ing 84-85
cle fi necl 134, 4 17 defined 85
d rop- dow n li st box 135. 139 Loca l scope , defi ned 84-85 , 4 17
ge uin g a l co nten ts of li s t 136 - 139 LOCA TE keyword 396

Microsoft Visual Basic Progra mmer's Guide


Microsoft Excel 443

LOF function 3 16, 340 Max property , scroll bars 141


Lag function 96 MaxButton property, forms 2 18,2 19
Loga rithms, ca lculating 96 Memory buffer
Logic error 228, 417 DLL routines and 383
Log ical centi meter 4 17 size far random-access files 334
Logical eq uivalence (Eqv) 88, 98 Menu , defined 4 17
Log ical inch 417 Menu bar, defined 417
Log ical nega tion (Not) 88, 98 Menu command
Log ical operators adding/deleting at run time 116 - 120
li st of 98 defined 417
use of 88, 99 Me nu control
Search Help for operator add ing check marks to 11 3 - 11 5
Lo ng data type 83 - 84, 386 add ing/de leting commands
l ,o ng integer 83 - 84, 386 at run time 11 6- 120
Loo p Search Help for menu
de fin ed 4 17 ass igning shortcut and access keys 120
Do loops 91-92 Caption property 111
ex iting 245-246 Click event 111
Far loops 92 - 93 creating first menu-driven application
nested 244,4 18 109 - 11 2
Search Help for loop creating separator bar 1 11 , 117
Los tFoc us event, text box 125 - 126 creating submenu s 11 0 - 111 , 421
Lower bound, arrays 254, 255 defined 417
Lowe rcase, translatin g to uppercase 105 , 127 , 133 enabling/di sabling commands 113
LPOS 396 hierarchical, defined 109, 416
LP RI NT state ment 396, 397 nam ing 110
LT ri 111 $ fun c ti on 11 5, 13 1 properties, events, and methods (list) Search Help
for me nu
Menu Design window
:1,,ig nin g ,h ort c ut dnd :tl·l·css kc: , l '.:0
,\ lai l icons (lea n Library) 404 creating menus 11 O- 1 11
Mai lbox icon Search Help for Menu Design wi ndow
creating animati on effect 165 Me nu Design Window command Search Help for
exa mple 404 Me nu Design Window command
Ma in procedure Menu name
as startup 220 defi ned 417
id le loo p and 273 spec ifying 1 1O
.MA K fi le 44 Menu separator bar 11 1, 11 7, 420
Ma ke EXE Fil e comm and (File menu ) Menu-d ri ven appli cation
use of 76 overview 109
Search Help for Make EXE File command T ry Me nus applicati on 109 - 112
Math operati ons Metafi le See Windows Metafile
ari thmeti c operators 75 , 98 Method
ca lculat ingPi 191 defined 9, 4 17
ca lc ul atin g squares, square roots 11 1- 112 li st of methods Search Help Jor methods
convertin g degrees to radians 19 1- 192 Microsoft Bas ic Professional Deve lopment System
Cos function 19 1 39 1 -398
fo rmul a far interest compounded dai ly 75 Microsoft Excel
arde r of precedence 75, 98 DDE app lication name 355
Si n and Tan functions 191 DDE statements, compared with Vi sual Basic 372
use o f pare ntheses 75 , 98 DDE ta pie nam es 355
usin g ass ignment statements fa r 82 exampl e links with 359 -360, 370, 372

Microsoft Visual Basic Programmer's Guide


444 Mi crosoh Presentat1on Manager

.\ 1icrosoft Presentati on Manager Modulo arithmetic 98 , 99


runnin g Setup from 15 Mouse button See Mouse eve nts
startin g Vi sual Bas ic fro m 17, 36 Mouse events
ve rsion requireme nts l 4 Buttan argument 196, 202 - 205
w ritin g applications for 76 dragging and droppin g control s 207 - 2 13
.\1 icroso ft QuickB as ic graphical mouse applicati ons 198- 201 ,
adapting code from 4, 391 - 398 204 - 205
compared with Vi sual B as ic 8, 80, 243 , 3 l 5 list of 196
.\ li crosoft Vi sual Basic Shift argument 196, 206
adapting other Basic code to 391 - 398 Search Help f ar mouse
compared with Pascal 8 Mouse pointer Search Help f or M o usePointer
co mpared w ith QuickB as ic 8, 80, 243, 3 15 Mou seDown event
eve nt -dri ven programming 7 - 8 breaking executi on durin g 239
in ~ta llingprogra m 14 - 17 Bullan arg ume nt 202- 203, 205
overview 3 - 9 defined 196
run-time fil e 76 DragMode prope rt y and 2 J 1
sta rting program 17 - 18, 36 graphical applicati ons 198, 200 - 201
syste m requirements 14 moving control s using 197 , 2 12 - 2 13
.\1icrosoft Windows Shift argument 206
ha ndl es 386 MouseMove event
runnin g Setup from 15 Buttan argume nt 203 - 205
running Windows applicati ons from shell program defined 196
106 - 107 graphical appli catio ns 199 - 20 1
sta rtin g Vi sual Basic from 17, 36 MouseUp event
ve rsio n requirements 14 Button argument 202 - 203 , 205
w ritin g appli cati o ns fo r 76 de fined 196
.\ li crosoft Word DragM ode prope rt y and 2 11
DD E application names 355 graphical appli cati o ns 200 -2 0 1
DDE state ment s compared with Visua l Basic 372 moving cont ro ls using 197. 2 12 - 2 13
DDF: topic nam e~ 355 Mo ve me th od
l' !J1...1 1111g \ Id ~l1c11 µ 1ug 1l-t1 l1 l\Jü lll0V ll1 g Cü llli ü l ~ .J llll L IIL k C\C lll l oo - l b !
.\ 1idS fun ction 27 1 moving cont ro ls and mouse events 197 .
.'vlidS sta te ment 128 2 12 - 2 13
.'vlin prope rty, scro ll bars 14 1 sy ntax 166
.\ linButto n property, fo rm s 21 8. 2 19 M sgBox functi o n 146
.'vi KD$ keyword 396 M sgBox statement
.\ IKI S key word 396 creating di a log boxes 146. 2 19
.\ lKLS keyword 396 syntax 146
v i KS$ keyword 396 Multidimensiona l arrays 255
.\ IKSMBF$ keyword 396 Multiline property, tex t boxes 124
.\1oda l fo rm 222 , 4 18 Multiple-form appli cati o ns
vlode less form 4 18 dialog boxes 2 17 , 2 18 - 2 19
.\ lod ify Co mm and$ command (R un me nu ) drag-and-drop operatio ns 207
use o f 240 exiting 226
Search Help fo r Modify Command$ command ge neral -purpose form s 2 16 - 2 18
.\ lod ul e Hide method 2 16, 224 - 225
de fin ed 37,43, 41 8 hiding form s 224 - 225
See a/so Global modul e Load state ment 2 16, 225 - 226
Search Help for modul e loadin g and di spl ay ing fo rm s 222 - 224
.'vlodul e window loadin g without di s pl ay ing fo rms 225 - 226
Search Help jór Modul e window moda l 222
.\ lodul e- level vari abl e 85, 4 18 selectin g icon for 22 1

Microsoft Visual Basic Programmer's Guide


0p enin g fil e s 445

,\11 u I Lipl e-form applications (continued) N umbers


Sho w method 2 16, 222-224 adding to list boxes 135
startup fonn or module 220 - 22 1 calcul ating squares and square roots 111 - 11 2
syntax 2 16 changing to strings 74, 75, 127, 156
Un load statement 216,226 fo rmatting 75, 128, 156 - 157
Sea rch Help for startup fonn intern ational fonn ats 128, 157
Vl ultipl ication (*) operator 75, 98 q uotation marks with literal constants 135
Vlu ltitas kin g 273 sequenti al-access fil es 420
testin g with relacional operators 87

\J
'\ía min g o
DDE appli cati on names 355 Object See Objects
DDE ite m names 355, 358, 365 Obj ect box 68, 69, 4 18
DD E lin ks 365 Obj ectname, defin ed 4 1
DDE state ments 372 Obj ects
DD E topic names 355, 358, 359, 360 - 36 1 defin ed 4, 6,4 18
event procedures 7, 41 , 67 - 68 naming 41 , 63, 67, 68
me nus 110 Search Help Jo r obj ects
obj ects 41, 63,67, 68 Oct$ fu nction 11 4, 13 1
va ri abl es 82 Octal numbers (base 8)
\:ega ti on (-) operator 98 defi ned 80
\:es ted 244, 41 8 Nu mber System application 113 - 11 5, 130 - 131
>i ew Form command (File menu) 37, 2 17 Office icons (Icon Lib rary) 406 - 407
'-Jcw Modul e command (File menu ) Sea rch Help for ON C OM keyword 396
Ne w Module command On Erro r GoT o statement
.' kw Procedure command (Code menu ) 94 adapting from other Basic code 398
'-lcw Projec t command (File menu ) Search Help for enabling erro r trap 282
:--Jew Proj ect command O n En-or Resume Next state ment 293 - 294
' • 1; "l' ,:- h:1r;1c 1cr O:\ KrY 1'c'_'\\1,1d .~%
co nvening fi les wi th nonstandard cha.rac te rs ON L OCAL ERROR GOTO 398
330 - 33 1 ON PLA Y keyword 396
load ing text in text boxes conta ining 124 O STRI NG keyword 396
no ne in rando m-access files 33 1 O TIMER keyword 396
u e in Tex t Edi tor application 326, 328 O pen Project co mmand (Fi le menu)
'-lew Page meth od 159 use of 43
., cx t Procedure command (Code menu ) Search Help Search Help fo r Open P roj ect com mand
fo r Nex t Procedure command O pen stateme nt
Nex 1 statemenl 244 binary-access fil es 350
:-S:o p (Draw Mode setting) 186 F il eOpener F un cti on procedu re 3 18 - 320
'formal pro perty, fil e list box 3 14 modes 3 17, 3 18
'-101 Copy Pen (Dra wMode sett ing) 186 random-access fi les 334
'-lot equal (<>J operator 87, 98 sequential fi les 320
\:01 o pera tor 88, 98 syntax 3 18
.'\íow fun ction 157 Ope ning fi les
. u 11 charac te r 382 bi nary-access files 350
'-Ju ll pointers 385-386 Fil eln fo di a log box, example 305 - 3 14
'\i umber See Numbers F i leO pener Functi on procedure 3 18 - 320
\; umbcr sig n (#) Open state ment, overview 3 17, 3 18
Doub le type-clec laratio n character 83 ra ndo m-access fi les 334
fonna ttin g num bers 75 , 156 Record Ed itor applicati on 34 1- 342

Microsoft Visual Basic Programmer's Guide


446 Opening fil es

Opening file s ( continued) Paste Link command (Edit menu)


sequential fil es 320 use of 356, 357
Text Editor applicati on 326-328 Sea rch Help fa r Paste Link command
Operating environment 41 8 Path
Operators di splaying with file-system control s 297
arithmetic operators 75, 98 See also Filelnfo dialog box; Launch Pad
defined 418 application
list of 98 Path property
logical operators 88, 98. 99 directory li st box 297
order of precedence 75, 98 file li st box 297
relational operators 87- 88 , 98 Pattern matching with Find and Repl ace commands
Option Base statement 398. 254 Sea rch Help f ar Pattern matching
Option button control Pattem property , fil e li st box 297 , 3 14
Click eve nt 129 PCOPY key word 396
defined 129, 418 PEEK keyword 396
properti es, events, and meth ods (li st) Sea rch Help Pen, defined 187
fa r option button PEN keyword 396
Toolbox location 48 Percent sign (% ), Integer type-declaration character 83
Valueproperty 129 Persisten! graphic 176, 41 8
work.ing with user input 129 - 13 1 Pi
Or operator 88, 98 calculating Pi 191
OUT keyword 396 converting degrees to radians 191 - 192
Ou tput mode, Open statement 3 17. 3 18 Picture
adding at design time 162
p adding at run time 163
data fo rmats (Clipboard) 267
P.AC KI NG.LST 15 fil e form ats 162
Paddin g moving and sizing 163 - 164
random-access fil es 333 See a/so !con
1ri111111i11~· 2:'i 1 \111nl, lfr l{I (m :c1:1ph ic,
l'-\G E DO\V I key Picture box control
key board handl ers and 275 adding pictures at des ign time 162
use in lmmedi ate wind ow 238 adding pictures at run time 163
Page numbers, printin g 159 ass igning access keys to 120 - 12 1
Page propert y 159 AutoRedraw property 176
P..\GE UP key A utoSize property 164
keyboard handl ers and 275 Cli ck event 103
use in [mm edi ate window 238 defined 158, 4 18
Pa int eve nt 176 DDE client 354
PA INT keyword 396 LoadPi cture function 163
Pa lette See Co lor pal ette; Too lbox mouse events recogni zed 196
PA LETTE keyword 396 Move method 197
Pare nthcses () mov ing and sizing 163 - 164
call s to Fun cti on procedures 80. 96. 396 mov ing in response to mouse events 197
use with operators 75 , 98 Pi cture property 162, 163
Pasca l. co mpared with Visual Bas ic 8 printing to 151 - 153
Paste command , creatin g 265 - 266 properti es, events, and methods (li st) Search Help
Pa ste co mm and (Edil menu ) fa r pi cture box
use of 162 res izing pi ctures 163- 164
Seorch Help .fár Paste comm and se lecting art for 164
Pa,1e Lin k co mm ancl , crca ting 365 - 367 Toolbox locati on 48

Microsoft Visua l Basic Programmer's Guide


Pro gramming la nguage ke yword s 447

Pic ture propert y Printer object


settin g at design ti me 162 C urre ntX, C urre nt Y properti es l 58
settin g at run time 163 de fin ed 4 19
Pixel EndDoc meth od l 59
defin ed 174, 4 18 fo nt properti es 158
settin g colo r pixel by pixel 181 NewPage me thod l 59
PLAY key word 396 printing to 158 - 159
PMAP keyword 396 Search Help fo r Printe r obj ect
Po int me th od Printer setup 18
defin ed 177 PrintForm me th od
re turnin g color value 18 1 sy ntax 159
Poi nt notatio n, accessi ng reco rds 26 1 using 159 - 160
Poi nte r (T oolbox) Printing
defi ned 4 19 di rec t to printer 15 8 - 159
T oolbox locati on 48 fo rma tting o utput 149 - 153
Po inte r icons (lea n L ibrary) 400 - 40 1 toforms 15 1- 153
Po ints, defi ned 174 to Immedi ate w i ndow 235 - 236
POKE (Excel statemen t) 372 new p age 159
POKE keyword 396 to picture boxes 15 1 - 153
Poki ng tables 154- 155
de fined 36 1, 419 using Pri ntForm method 159 - 160
LinkMode property and 36 1 Search Help for print code; print forrn
poki ng data to Microsoft Excel 370 Procedure See Proced ures
Polygo n, d rawi ng 183 Procedure box
POS keyword 396 defin ed 4 1,68, 419
Position, setti ng via Properties bar 64 _s electing even ts from 68 - 70
Precede nce, a rder of 75 , 98 Procedure S tep command ( Run me nu )
Presenta ti o n Manage r See Microsoft Presentation use of 234
Ma nager Search Help fo r Procedure Step comma nd
PRESERV E kcy\\'ord 196 Procedure steppin ~ ~' l . 119
l' RESET keyworJ 39 7 Proced ures
Prev io us Procedure comm and (Code menu ) Search creating, qu ick way 94
Help for Prev ious Procedure comma nd defin ed 4 19
Prime numbe r, tes ting for 245. 246 event procedu res vs. ge neral procedures 93 -94
Prin t # state me nt 395 scope of 94
Print comm a nd (Fi le menu ) tes ting 238
use of 18 See a/so Event procedure ; Functi o n procedure ;
Search Help for Print co mmand Ge neral procedu re ; Sub procedu re
Print m e th od Search Help for procedures
adapting Prin t statements from other code 395 Program -log ic e rrors See Enors
as gra phics me th od 177 Programmer's Cuide I O, 11
A utoRedraw prope rt y and 176 Programming
fo nt properti es and 149 event-dri ve n approach 4 - 5, 7 - 8
printin g GU I 4 , 6
to fo rms and picture boxes 15 1 - 153 tips
to lmmedi ate w indo w 235- 236 error ha nd ling 288
to printe r d irec tl y 158 - 159 pl aceme nt of type and co ns ta nt defi niti o ns 258.
ta bles 154 - 155 278
sy ntax 15 1, 158 progra m des i_g n 228 - 229
Search Help f or print code : print fo rm w ritin g even t proced ures 67 - 68, 130
P1·int zo ne 154,4 19 Programmi ng la ng uage keywords Search Help for
language

Microsoft Visual Basic Programmer's Guide


448 Project

Projec t Quick.B as ic See Microso ft Qui c kBasic


dcfincd 36 ,4 19 Quitting
ite ms in 43 multiple-form applications 226
o pe nin g/closing 43 Setup program 16
storin g project files 44 Visual Basic 43
Sea rch Help f ar project ; scree n properties Search Help far quit
Projec t window Quotation marks, with literal constants 135
defined 36, 419
ope nin g/closing 36
Search He/p far Project window R
Projec t Window com mand (Window menu) 36 Radian 191 , 192
Properti es Radio button See Option Button control
default settin gs 38. 58. 41-+ Radius argument. Circle method 189. 190
dcfi ncd 8. 4 19 Random access
m iti a li zing 222, 226 compared with binary access 350 - 35 1
pass in g in DLL routines 386-387 defined 3 16,3 17 , 419
pass ing values of, in arguments 97 See a/so Random-access fil e
printin g and testing values of 237-238 Random-access file
re triev ing va lues, assignment statements 8 l. 82 creating/adding records 332 - 335
ro le of in Vi sual Basic 58 defining records 332 - 333
se ttin g via Get and Put statemen ts used with 334- 335
assignment statements 8 1 index codes 340
code 42 , 64 open ing file s 3 17. 3 18 - 320, 332, 334
Prope rti es bar 38-40. 58- 64 overview of file access 3 16, 3 17
use r input 64 Record Edi tor appl ication 336-350
"·ntax for referrin g to 74 storing records 33 1
, 1c,, in g property settin gs 58 user-defined type and 26 1
Seurr-h Helpfor properties when to use 3 16.317
l'1,1pcn1c, bar Random mode, Open state ment 3 17, 3 18
dcfincd 1X . --1 ¡ q RFl\nrvJFT\'T 1~
t 1upc1t 1c, 11,t l>u,\ _,'). Y:! lHJ l< ead ün Iy pro1Jl:rt y. 1!le li q bo" 3 14
,c llin g properti es via 38-40. 58 - 64 Record
Se ttings box 39, 59 , 420 binary access file 3 16. 3 17,350
\ ho rt c uts for se ttin g propeni es 6 1 - 62 random-access fil e
Seurch Ht'lp jór Properti es bar access ing by number 3 17
Propc ni es li st box add ing data to 332 - 335
loca tion on Properti es bar 39. 4 19 defining 332- 333
u,ing 59-60 Get and Put stateme nts used with 334-335
Prn pc rt y See Propertics Len function 3 19. 334
PSct method opening file, specifying length 334
desc ribcd 177 overview 3 16, 317
sc ttin g co lo r pix e l by pi xe l 18 1 Record Editor appli cation 336 -3 50
,y nta x 18 1 retri ev ing by number 348- 350
l'u,h button See Command bu tt on co ntro l Seek sta tement and functi o n used with 352
l'ut , ta1e mcnt storage 331
file types uscd with 3 16 Record Ed itor application
random -access file s 334 - 335. 350 -35 1 AddRecord_Click event procedure 345
CheckE mOut Functi on procedure 343
Q CleanUpFile Sub procedure 348
code 337 - 350
Q8Co lo r runction 179 Dc le1eRecord_ Click eve nl procedurc 345 -346
() uc, ti o n mark ('I), printing with 236. 239 ExitButton_ C li ck eve nt proceclure 346 - 34 8

Microsoft Visual Basic Programmer's Guide


Save File command 44'.

Reco rd Editor applicati on ( can tinu ed) Rock ' n' Ro l! application
Form_ Load event procedure 339 -340 displaying Gro upCho ice for m 223 - 224
global modul e 338 exiting 226
HScroller_Change event procedure 349 - 35 0 hiding forms 224 - 225
inte rface 336 properties, genera l-purpose fo m1 s 2 17 -2 19
NextRecord_Click event procedure 344 specifying icon 22 1
OpenFi le_Click even t procedure 34 l -342 startup form 220-22 1
PreviousRecord_Click eve nt procedure 344 Rounding
retrieving records by nu mber 348 - 350 Currency data type 80, 84
ShowRecord Sub proced ure 340 - 34 1 floating-point numbers 84
Rec tangle, drawing 384 - 385 integer di vision 99
Re Dim statement RTrim$ function 251
compared with Dim 256 /RUN 17
creating dynami c arrays 256, 397 RU N keyword 397
Refres h method 275 Run me nu commands
Relationa l operators See specific cammand names
li st of 87, 98 Search Help far Run menu commands
use of 87- 88 Run mode, defined 229
Remove File command (File me nu ) Run time, defined 37,229,4 19
use of 44 Run-time appli cation
Sea rch HelpfarRemove Fi le command creating 76
Re rnoveltem method, list boxes and combo boxes 136 requirements for 76
Re naming files Search Help far executab le file
tips 44 Run-time error
Save Fi le As cornmand 44, 45 defined 22 8, 420
Sea rch Help far Save Fil e As command codes
Re naming proj ec t DDE erro r numbers 373
Save Projec t As co rnm and 45 list of error codes Search Help fa r trappab le
Sea rch Helpfar Save Projec t As cornma nd errors
"·¡, l:1cc u11111":111d 1 C ,de •pc1111' , ,.11ff l1 //,./1, li>r ··•·t ,·;" :,.
pattern rnatchin g: Replace command 292 - 293
REQUEST (Exce l stateme nt ) 372 messages
Reserved word retrieving with Error$ 28 1
defined 82. 4 19 li st of error messages Search Help far
Vi sual Basic language keywo rds Search Help far trappable errors
language See alsa debuggin g
Res izing fo rms Sea rch Help far run-ti me error
BorderStyle property 2 18,2 19 Run-time fi le (VBRUN 100.DLL) 76
Height and Wid th properties 64, 168 Runnin g program See Exec uting code
Tex t Ed itor app li cati o n 329
Restan co mmand (Code menu) Search He/p far
Res tart command s
RESTORE keyword 397 SADD keyword 397
Re sume line 283, 285, 286 Sample appli cations See Applications, sampl e
Resume Next statement "Sample Application s," tutoría! 20
ex iting error-hand ling routine 283 -286 Save File As command (Fil e menu)
use with un ant icipated e rrors 286 use of 44. 45
Res ume state ment 282 , 283 -286 Search Help far Save Fil e As command
Rcturn state ment 398 Save Fi le comrnand (Fi le menu )
RGB fun cti on use of 45 , 73
DoColor exampl e 143 Sea rch Help far Save File command
sctting colors 179

Microsoft Visual Basic Programmer's Gu ide


450 Save Project As command

Save Project As command (File menu) Scroll bar controls


use of 45 add ing to Record Editor 349 - 350
Search Help for Save Project As command Change event 14 1, 142
Save Proj ec t com mand (Fil e menu ) gettin g user input 140 - 143
use of 45 hori zontal 140, 422
Sea rch Help for Save Project command LargeChange property 141
Save T ex t comm:rnd (Code menu ) Max property 141
use of 45, 73 Min property 141
Sea rch Help fin· Save Text command properties, events, and methods (list) Sea rch Help
Sav in g for scroll bar
binary vs. ASCII formal --Vi. 73 settin g color, example l 42 - 143
li st of commands 45 SmallChange property 14 1
Text Editor appl ication 32:s - 326 Toolbox locations 48
Search H<!lp fo rsa\C Yalue property 14 1
Sca le vertical 140, 422
creatin g custo m sc ale 172- 173 Scrol!Bars property, text boxes 124
defined 17 1 Seek function 352
resettin g to defa ult 175 Seek statement
ScaleM ode property 174 positioning file pointer 352
setting with Scale me th od 174, 175 use with different file types 3 16
settin g with sea le properties 171 - 173 Select Case statement
Sca le me th od control structure 86, 90 - 9 1
resettin g to de fault 175 Case E lse clause 91
se ttin g sca le 174. 175 syntax 90
sy ntax 174 Selecting tex t (c ut and pas te commands) 264.
Sca le He ig ht property 265-266
Circl e meth od and 189 SelLength property, text boxes and combo boxes 264
se ttin gscale 172 - 173 SelStart property , text boxes and co mbo boxes 264
Scale Left propcn:- 17:. - 173 SelTex t property text boxes an d combo box es 264
Sca leMnclc rrn pn t\ 17 1 Semicnlnn (:). Print nwth nd ~nd 1 ~ 1 1 ~.., .., 1 0
::>c·.ilclup p1upc 1l \ I ,_ 1 1., SendKeys stateme m 375 - 376
Sca leWidth propcrt y Separatorbar 111 , 11 7,420
Circle meth od and 189 Sequenti a l access
se tt i ng sca le 172 - 173 defin ed 3 16,3 17,420
T ex tWid th compared to 153 See also Seq uen ti al-access fil e
Scope Sequential-access file
compari son of variab le scope 84 numbers in 420
constants 258 open in g file in sequ e ntial mode 3 17, 318 - 320
defined 82.420 overview of fil e access 3 l 7, 3 18, 320
va ri ab les 8--1 - 86. 394 T ex t Ed itor app licati on 320 -330
SCREEN keyw ord 397 whentouse 3 16,3 17,320
Sc ree n object Server application , defi ned 354, 420
Act iveControl prope rt y 266. 365 Server link
defi ned 420 creating 357
Search Help .fiir Scree n obj ec t de fin ed 357,420
Sc reen properti es Sea rch Help fo r screen properties eve nts 363 - 364
Screen update. Re fres h mc th od 275 prope rties 360 - 36 1
Sc ribbl e appli catinn spec ifying application name 36 1
one- button vc r~ion 199 - 20 1 te rminatin g 363
two-button vc rsio n 204 - 205 updatin g 37 1
See a/so DDE (dynam ic data exc hange)
Seo rch Help for lin k

Microsoft Visu al Basic Progra mm er's Guide


Startup form or module 451

Set ext Stateme nt comm and (Run menu) Shortcut keys ( con tinu ed)
use of 235 SHIFT+F8 (Procedure Step command. Run menu)
Search Help for Set Nex t Statement command 234
Se t Startup Form command (Run menu ) Visual Basic shortcut keys Search Help for
use of 220 shortcuts
Sea,:ch Help for Set Startup Form command Show method
SetData method 267 loading and displaying fo rms 222 - 224
SetFocus method 340 syntax 2 16
SETMEM keyword 397 Sin 191
Se tText method S ingle data type
copy ing text to Clipboard 265 - 266 defined 83
syntax 265 highest value 84
Se tting Single Step command (R un me nu )
default settings 38, 58, 414 use of 233
defined 8,38, 420 Search Help for Single Step co mmand
Settings box 39, 59, 420 Single stepping
Sctup program defined 233,420
bac king up disks 15 using 233 - 234
getting Help 16 Single-precision numbers, in random-access files 333
need for 13 Sizing handle 53, 420
quitting 16 Sizing objects
re installing Visual Basic 16 BorderStyle property 218, 2 19
running Setup 15 - 16 Hei ght, Width, and Autosize properti es 168
SETUP.EXE using Properties bar 64
desc ri bed 13 usi ng sizing handles 53
See a/so Setup program Search Help for size
Shc ll app li cation, Proj ect Pl anner 106 - 107 S lash
She ll function (/) di vision symbo l 75 , 99
co mmand buttons and 105 - 107 (\) integer di vision 99
•n° n 11 en, 1n:inr1, ·"~d 1 ! '-' Sl.EEP kC)\lüld 39 ~
~ta rting appli cati ons using DDE 369 SmallChange property, scroll bar 14 1
syntax 105 Salid line, DrawStyle setting 185
See a /so Launch Pad app licati on Sort See Sorted property
Sl11ji arg ument Sorted property, list boxes and combo boxes l 35
key board handl ers and 276, 277 - 278 SOUND keyword 397
mouse events and 196, 202 - 206 Source (drag-and-drop operati ons) 209 , 420
placement of constants 278 Source argument, DragDrop eve nt 209
S HIFT key, testing for Space character 333
key events 277 - 278 Spaces
mouse events 206 LTrim$ 115 , 13 1
\ IIIFT+ F8 (Procedure Step command) 234 padding ·trailing spaces, random-access files 333
Shonc ut keys RTrim$ 25 1
creating for users 120 - 12 1 Spec ial charac ters, sending w ith SendKeys 376
CTRL+ BR EAK 230 Square root, ca lculating 11 2
de fined 420 Start command (Run menu)
FI key (Help) 24, 25 use of 73 , 229
F5 key (S tart comm and, Run menu) 42 Search Help for Start comm and
FX key (S ingle Step command , Run menu ) 233 Start ing Visual Basic 17, 36
F9 key (Togg le Breakpoint command, Run menu) Startup form or modu le
23 1 creat ing 220 - 22 1, 392
lmmediate window key s 238 - 23 9 us ing when writin g idl e loops 273
Sea rch Help for startup form

Microsoft Visual Basic Prog rammer's Guide


452 State argument

S1t11e arg um e nt , DragOver event 21 O Sub procedure ( con1inued)


State me nt sy ntax 95
defined 420 typographi c conventions for xv
exec utable statement 415 writ ing 67 , 95-96
sy nta x 42 Search Help for Sub procedure
See a/so Ass ig nm e nt statem e nt ; Executing code Submenu , creating 110-111 , 421
State me nt block , define d 67 Subprogram See Sub procedure
Stati c keywo rd Subroutine See Sub procedure
dec la rin g a rrays of variables 253, 254 Subtraction (- ) operator 98
dec larin g va riabl e 247 SW AP keyword 397
scope of stat ic va riables 85, 247 Symbolic constants, decl a rin g 258 - 259
S tat ic va riabl es Syntax conventions x 111 -xv
define d 420 Syntax checkin g
d cc larin g 247 , 253 , 254 defined 7 1, 421
scope of 85 , 247 Search Help for sy ntax c hecking
Step keyword Sy ntax Checking command (Code me nu) Search Help
For loop 93 for Syntax Checking command
with grap hi cs me thods 187 - 188, 189 Syntax e rror
ST ICK keywo rd 397 defined 228, 421
S top sta te me nt resolving, in imponed B as ic code 396
c rea tin g breakpoints with 230, 233 Search Help for syntax c hecki ng
in e rror-ha ndling routines 288 System commands, exec utin g with command buttons
StrS function J05 - 107
com pared w ith Format$ 156 System property, fil e lis t box 3 14
converti ng numeric data to s trin g dat a 75 , 81, 114 System requirements, for Vi sua l Bas ic 14
STR IG kcyword 397 System topic (DDE) 355. 369
St rik e thru. font fo rm a l 150
S tring da ta type
dec laring 8.1 T
ni 1 ,·n 111 in, · , ·>iH I , R.., ,R, T :1b r,:·1 · ;· ! ~5
Tab key
co ncatenat ion 100 moving amo ng co ntrols 121 - 122
co nve n ing numeric dat a to strin g dat a 75 , 8 1. 114 recognized by KeyPress 275
convening stri ng d a ta to numeric data 74 Tab order
fixed- leng th 25 1, 333 co ntrolling 12 1- 122
tes tin g w ith re la ti ona l operators 87, 100, 127 defined 120,42 1
trans latin g Keyascii to String data type 127 Tablndex property 122
var iab le- le ngth 25 1, 385 Sea rch H elp for tab order
S ty le property T abl nd ex propert y 122
combo box e ve nts a nd 139 Tables, printing
se tt i ng fo r settin g tabs 155
drop -clown co mbo box 134 using built-in ta bs 154
drop -down li st box 135 Tabs
s impl e combo box 134 c rea tin g tab space in tex t boxes 330
S ub Main proccd ure printing tab les wi th built-in tabs 154
desc ribed 392 printing tables with custom tabs 155
Search Helpfor Sub Main T abS top property 121
Sub proccclure Tag property 209
com parecl with Function proced ure 94, 96 Tan 19 1
clec lar ing DLL routines as 379 Target (drag-a nd -d rop operations) 209, 42 1
dcfinccl 42 1 T e mpera ture Co nve rte r 147 - 148
cxi tin g 246

Microsoft Visual Basic Programmer's Guide


Timer control 45

Template, code Tex t box control (con tinued )


defined 4 1, 4 12 Text property 39, 42, 64
disp layed 68, 70 Toolbox location 48
TERMlNATE (Excel statement) 372 user input
Testin g accep tin g 66
command-line arguments 240 preventing 147
data and procedures 235 - 239 working with 124 - 128
halting at errors 230-233 validating data in 125 - 126
procedure stepping 234 word wrap J 24, 328
setting next statement 234-235 Text Editor app lication
single stepping 233 - 234 CheckltO ut Sub procedure 323 - 324
using breakpoints 23 1 - 233 code 32 1 - 329
us ing Stop statement 233 design 320 - 322
See a/so Debugging error handling 325
Search Helpfortest run Ex itButton_Click event procedure 323
Text Filelnfo dialog box 328
copyi ng to/from Clipboard 265 - 267 Form_Load event procedure 325
creating copy, cut, and paste commands Form_Resize event procedure 329
265-266 GetName Sub procedure 323 - 324
fo rmatting g lobal module 323
fonts 149- 150, 154 interface 321
output to form or picture box 151 - 153 OpenButton_Click event procedure 326 - 328
output to printer, direct 158 - 159 OverWrite Sub procedure 324- 325
tabular data 154 - 155 SaveButton_Click event procedure 326
selecting text for cut-and-paste operations 264 savi ng fi les 323 - 326
SelStart, SelLength, SelText properties 264 using procedures from 329 - 33 1
Tex t (ASCll) formal, saving as 45 Text property
Te xt box control combo boxes and list boxes 135 , 136 - 137
assigni ng access keys to 120 - 12 1 defined 38
C'apti on propert y 39 methods o f sett ing 64. 8 1
c hanging, reSLricting ke ys troke~ J 26 - 12il tex.t boxe~
creating copy , cut, and paste commands 264 - 266 empty string 40, 63
Ct!Name property 39 setting 39, 42, 63, 64
DDE client 354 TextHeight method 153
defined 49,421 TextWidth method 153
displaying text, first examples 42, 66 Time
drawing 37 - 38 Alarm Clock app lication 27 1- 272
edit contro l, defined 49 converting A.M ./P.M . 270 - 27 1, 272
edit field , defined 49 Digital Clock app lication 270 - 27 1
e mpty string 40, 63 formatting 157
Enabled property 147 retrieving curren! time 11 2, 270, 272
line breaks 124, 328 Time$ function 11 2, 270, 272
LostFocus event 125 - 126 Time-ou t error
maximum characters 320 avoiding with DoEvents 374 - 375
maximum line length 328 interrupting DDE befare 360
Multiline property 124 Timer control
properties, events, and methods (li st) Search Help associated with form 268
fa r text box Ct!Name property 269
retriev ing data from 66, 74 defined 6, 421
Scro llB ars property 124 Enab led property 269
se lect ing, highlighting text in 264 Index property 269
Se lLength , SelStart, Se!Text properties 264 initia li zin g 269

Microsoft Visual Basic Programmer's Guide


454 Timer control

Timer control (callli1111ed) Tmncation 99


Interva l propert y 268, 269 Try Menus app li cati on
placing on form 268 - 269 code l 11- 1 12
properties. events, and methods (list) Search Help interface 109 - 11
far timer Tutoría!
Timer event 268, 269 - 272 described I O, 20
Too lbox location 48 mnning 19 - 20
Timer event Tutoría] command (Help menu) 19
activati ng 269 Twip
responding to 269 - 271 default sca le 174
setting an alarm 27 1 - 272 defined 174. 421
setting interval 268 , 269 inch and cen timeter equivalents 152, 167
Timer function 268 Two-dimensional arrays 255
Tit lc bar 42 1 Type See Data type: Type statement
To keyword , lower bound 254 Type mismatch , fixing 230 - 231
Toggle Breakpoint command (Run menu) Type statement
use of 23 1 placement of 257. 260, 332
Sea rch Help far Toggle Breakpoint command syntax 260
Toggle effect user-defined data type 260- 261 , 332
controls 169 Type-declaration charac ters 83, 421
icons 165 Type .. .End Type statement
Toolbox creating user-defined type 260-261, 332
adding custom controls to 378 placement of 257 , 260, 332
defined 37, 48.421 TypeOf keyword
icons 48 determining type of control 249 - 250
opening 48 use wit h mouse even ts 209
pointer 48 Typographi c con\'e ntion s, followed in manual
se lecting tools from 37 Xlll - XY
Search Help fa rToolbox
Tnnlhrn comm and (Win do\\' menu ) -l ~
1 up prupcrt )
defined 166 UCase$ function 105
settin g 64. l 66 Underline. font fom1at 150
Topic (DD E) See DDE Topic Undo command (Edil menu ) Search Help far Unclo
Tracing execut ion command
stepping through statements 233 - 235 Unload statement
Search Help far trace execution syntax 2 16
Traffic icons (lcon Library) 408 unloading
Traili ng spaces , trimming 25 1 control s 118. l 69 , 17 1
Transparent form ~ 226
DrawS tyle setting 185 menu item s 1 18
font 150 Upper bound
Trapping errors See Enor-handling fixed arra ys 25 3
Trimming spaces mu ltidimen sional arrays 255
LTrim$ 115 , 131 User, defined 421
RTrim$ 25 1 User input
TROFF keyword 397 check boxes 132 - 133
TRON keyworcl 397 InputBox$ 118, 143 - 144
True li st box es ancl combo boxes 134 - 139
Boo lean express ions 99 option buttons 129 - 13 1
cleclaring as symbolic constan! 258 scroll bars 140 - 143
intege rfor 107, 108 se tting properties via 64

Microsoft Visual Basic Programmer's Guide


Writing icons 45!..

User input ( co111i1111ed) Verti ca l scroll bar control ( continued)


text boxes getting user inpu t 140 - 143
accepting 66 LargeChange property 14 1
preventing 147 Max propert y 14 1
working with 124 - 128 Mi n property 14 1
User interface, draw ing 37 properties, events, and methods (list) Search Help
User prompt for scro ll bar
using InputBox$ 118, 143 - 144 Smal!Change propen y 14 1
See also User input Toolbox locati on 48
User-defined data type Value propen y 14 1
creating 260 - 26 1, 332 View Code comm and (Vi ew menu)
defined 257 use of 229
DLL ro utines and 38-l - 385 Sea rch Helpfor View Code command
US ING$ keyword 397 VIEW keyword 397
Visible propert y
control s, hi ding/showing 107, 168 - 169, 249
fi le-system controls 3 14
Val function fo rms, checki ng hidden status 225
converting stri ngs to numeri c data 74 , 13 1 Vi sual Basic See Mi crosoft Visual Basic
decimal separator and 128
ex trac ting hours from stri ng variabl e 27 1
retri eving nu meric value of propert y 82, 1 15 w
Va lue property W AIT key word 397
chec k box 132 Whi le ...Wend
opti on button 129 compared with Do Whil e 9 1
scroll bar 14 l ex itin g 245
Vari ables Wic!t h # 398
arra ys of variabl es 253 - 256 WIDTH LPR I T keywo rd 397
data types 83 - 84 Wi dth propert y
dc f;1ult typc 2) 9 2(,() lc'Sl/ 11 1" c<•/111< ih'-
defined 74, 82, 422 ScaleWidth compared with 172
fixed-length stri ngs 25 1 setti ng 64
in global modu le 257 Window
initi ali zing 125 as fo rm 37
naming conventi ons 82 See a/so Form
printing and testing va lues of 235 - 238 Sea rch Help fo r winc!ow
scope 84 - 86, 394 WINDOW keywo rc! 397
static vari ables 247 Window menu commands
storing data in 82 See speciflc command names
typographi c conventi ons for x v Search Help fa r Window menu commands
user-defin ed type 260 - 26 1 Wi ndo ws See Microsoft Winc!ows
VA RPTR keyword 397 Windows metafi le
VARPTR$ keyword 397 elata fo rm al (C lipboarc!) 267
VA RSEG keyword 397 defined 4 17
VB .EXE icon 36 fi le ex tension 162
VBRUN I00.DLL fi le 76 .WMF fil es 162
. VBX file, custom cont rol fi le 378 Word wra p 124, 328
Ve rti cal scroll bar control " Worki ng with Visual Bas ic," tu tori al 20
Change event 14 1. 142 Write # statement 3 17
defined 422 Writing ico ns (lcon Library) 408 - 409

Microsoft Visua l Basic Programmer's Guide


456 X arg um e nt

X y
X arg um elll Y argume nt
DragDrop event 209 DragD rop event 209
mouse events and 196 , 197 mouse events and 196, 197
Xor operato r 88. 98 Yield control
Xo r Pe n (Draw Mode setting) 186 in DDE con versatio n 374 - 375
writing idle loops 273-275

z
Zero, fo rm atting numbers 75 , 156

Microsoft Visual Basic Programmer's Guide


1
1
1
1
1

You might also like