visual basic notes

118
Fundamentals of Visual Basic U.E. Callaway Plant Course Notes Kevin M. Hubbard, CMfgE

Upload: erica-miller

Post on 02-Apr-2015

171 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Visual BASIC Notes

Fundamentals of Visual BasicU.E. Callaway Plant

Course NotesKevin M. Hubbard, CMfgE

Page 2: Visual BASIC Notes

I. The Visual Basic Development Environment

The Visual Basic language and development environment are powerful tools. Using these tools, the developer can create advanced Windows based programs, often in a fraction of the time required to create the same application using other languages, such as C/C++.

The name Visual Basic implies that much of the program development performed using this language is accomplished visually. Program development is performed in two concurrent steps: Visual Programming and Code Programming. Programming is done during design-time, and program execution occurs during run-time.

Visual Project Development: The Project, The Form, Control Objects, Basic Modules and Procedures

Each Visual Basic application is known as a project. A project is a collection of forms, modules and controls that function together to form an application. Only one project may be open at any given time in the Visual Basic development environment.

The form is the most basic building block for the visual implementation of a Visual Basic program. The form is an object. Visual Basic objects possess properties which control the way that each object appears. Properties also control the manner in which each object responds to events. Events are occurrences which may be user initiated (for example, the mouse_click event) or generated by other objects or by the system.

The form acts as a container, holding other Visual Basic objects needed for the implementation of the program, such as command buttons, radio buttons, text boxes, labels, etc. Figure 1 shows a typical form which contains a number of objects. This form is shown during run-time.

Figure 1: A Visual Basic Form

1

Page 3: Visual BASIC Notes

Objects are placed on a form by double-clicking the toolbox located at the left of the screen. This toolbox is shown in Figure 2.

Picture BoxText BoxCommand ButtonRadio Button

LabelFrameCheck BoxCombo Box

Hor. Scroll Bar

Timer

List Box

Ver. Scroll Bar

Drive List Box

Dir. List BoxFile List Box

Figure 2: The Visual Basic ToolBox

Each object can experience a number of events. Visual Basic’s Help gives a list of events for each object. Each event that an object can experience may have a segment of code associated with it. For example, one event which may be experienced by the command button object is the mouse_click event. The code segment that is executed each time that the mouse_click event occurs on a command button is known as the command button’s mouse_click procedure. A Visual Basic procedure is analogous to a BASIC sub-program or FORTRAN subroutine. The code for any event procedure is executed either:

1. When the object to which the code is attached experiences the event with which the code is associated.

2. When the event procedure is invoked by another program statement.

Each object has its own event procedures. For example, if we create three command buttons with three different names, three sets of command button event procedures will be created for us. We may then write code into these event procedures.

2

Page 4: Visual BASIC Notes

HINT: It is good practice when naming controls to assign a control name which begins with (say) a three letter abbreviation which identifies the control type. Some suggested abbreviations are:

cmd - Command Buttonopt - Option Buttonchk - Check Boxmnu - Menu Itemdir - Directory List Boxfil - File List Boxdrv - Drive List Boxlbl - Labelfrm - Framelst - List Boxfrm - Form

A special case of the Visual Basic procedure is the general procedure. These are procedures which are not associated with a particular control or event. General procedures are called from within other procedures, and may contain code which must be called repeatedly from different control object events.

Other Visual Basic statements may be contained in Basic Modules. Basic Modules are useful when a project contains several forms, and must make use of global variables visible to all forms. Global variables may be declared using the GLOBAL statement in a Basic Module external to all forms.

Object Properties

As we have discussed previously, each object (including the form) possesses a number of properties. The number and type of properties associated with each object varies with object type. Some of the properties possessed by most objects are:

Name : Identifies the object and all associated procedures.Caption : Displays messages, etc., on the object both during design-time and during run-time.Height : Defines the vertical dimension of the object.Width : Defines the horizontal dimension of the object.Top : Defines the vertical location of the top of the object. The Top property is measured

positive down from the top of the screen or form, depending on context.Left : Defines the horizontal location of the left side of the object. The Left property is

measured positive to the right from the left side of the form or screen, depending on context.

Enabled : Determines whether the form or control can respond to user generated events.Visible : Determines whether the form or control can be seen by the user during run-time.

3

Page 5: Visual BASIC Notes

Object properties can be set/changed during design time using the properties window. Properties can also be changed during run-time from code. For example, if we had created a form named frmshowme during design time, and wished, during run time, to change its caption to “I’m showing you”, we could execute the code statement:

frmshowme.caption = “I’m showing you”

When object properties are referenced in code, the syntax shown in the statement above is used. In general, the syntax for referencing and changing object properties from code is:

objectname.propertyname = newvalue

Note that forms and controls can be moved and sized during design time either by:

1. Using the mouse.2. Specifying numerical values for Top, Left, Height and Width in the Properties

Window.

II. Code Generation

Many of the keywords used by QuickBASIC are also used by Visual Basic. Some major differences between the two languages exist in the areas of:

1. User input: Visual Basic does not support the use of INKEY$, INPUT, LINE INPUT, or other keyboard driven statements that you may be familiar with in the QuickBASIC context. During this short course, we will discuss the ways in which Visual Basic receives user input from both the mouse and the keyboard.

2. Variable Definitions: Visual Basic supports the use of the option explicit statement. The option explicit statement is a powerful tool which deals with mis-spelled variable names and confusion in code where the scope of a variable is not clear. The option explicit forces the declaration of all variables, and is placed in the general declarations procedure of a form. Variables are declared using the DIM, GLOBAL, REDIM, and STATIC statements.

3. Variable Types: Visual Basic supports all of the variable types used with QuickBASIC. In addition, Visual Basic allows the programmer to use the variant data type. A variable declared as a variant may contain either a string or a numerical value. The variant data type is Visual Basic’s default. For example, the statement:

DIM thisvariable

declares the variable thisvariable as a variant.

4

Page 6: Visual BASIC Notes

The data types supported by Visual Basic are shown in Table I.

Data Type Suffix Storage Size RangeInteger % 2 bytes -32,768 to 32767

Long (Long Integer) & 4 bytes -2,147,483,648 to 2,147,483,647

Single (Single Precision Floating

Point)

! 4 bytes -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values

Double (Double Precision Floating

Point)

# 8 bytes -1.79769313486232E308 to-4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values

Currency (Scaled Integer)

@ 8 bytes -922,337,203,684,477.5808 to 922,337,203,685,477.5807

String $ 1 byte/character 0 to approximately 65,500 bytes.Some storage overhead required.

Variant none As Appropriate Any numeric variable up to the range of a Double or any character text.

User-Defined(using Type)

none Number Required by Elements

The range of each element is the same as the range of its fundamental data type, listed above.

Table I: Visual Basic Data Types

Event Driven Programming

The generation of code for event driven programming requires a slightly different mind-set on the part of the programmer from that of procedure driven programming as used in traditional languages such as BASIC and FORTRAN. In event driven programming, sections of code (procedures) are executed only when the object to which that code is attached experiences the event for which the code is written. For example, consider the following BASIC code fragment

SCANAGAIN: USERINPUT$ = INKEY$ ‘poll for user inputIF USERINPUT$=“” THEN GOTO SCANAGAIN ‘if no input is received, poll again

This program fragment puts the procedure driven BASIC program into a loop. Program execution exits the loop only if the user hits a key. At this point, program execution continues with the statement following the IF-THEN statement.

5

Page 7: Visual BASIC Notes

Using Visual Basic, we might create a command button called cmdstart, with a caption of START. If the user clicked the START button, the following code would be executed:

SUB cmdstart_clickstartflag=1-startflag ‘toggle the startflag variable between zero and oneEND SUB

Note: The variable startflag must be visible in all procedures in the form. In order to accomplish this, we must declare startflag in the General Declarations procedure.

Other procedures in the project might use as their first line of code:

IF startflag = 0 EXIT SUB ‘if the start flag is not equal to 1, exit this procedure

This line of code prevents execution of the procedure if the user has not clicked the START button.

The Form Load Event

The Form Load event, by default, is the first event to occur upon start-up of the application (for a startup form). If there are multiple forms in a project, the Form Load event for each form occurs when the form is loaded (as a result of a reference to an unloaded form’s properties or controls). The form load procedure has the syntax:

Sub Form_Load()

EXECUTABLE STATEMENTS

Exit Sub

Form Load event procedures contain initialization code for a form which may specify default settings for controls, cause contents to be loaded into combo and list boxes, initialize form-level variables, etc.

6

Page 8: Visual BASIC Notes

Note: When a property on an unloaded form is referenced in code, the form is automatically loaded, but is not made visible to the user. To make the new form visible, you may use the SHOW method, or set the VISIBLE property of the new form to true in its FORM_LOAD event procedure. Events which are related to the Form Load event are:

Activate: Occurs when a form becomes the active window (the window that appears in the foreground with a highlighted border or title bar).

GotFocus: Occurs when an object receives the focus (i.e., is able to receive user input using either the mouse or keyboard). In the Windows environment, only one object hold the focus at any given time. Objects can receive the focus only if their Enabled and Visible properties are set to TRUE.

Paint: Occurs when part or all of a form or picturebox is exposed after it has been moved or enlarged, or after a window that was covering the object has been moved out of the way. Using the Paint procedure, the programmer can ensure that graphics on the form are repainted when necessary. Note that if the AutoRedraw property of the object is TRUE, repainting is done automatically, so additional code in the Paint procedure becomes unnecessary.

Resize: Occurs when a form first appears, or the size of an object changes.

The Click Event

This event occurs when the user presses and releases a mouse button while the mouse pointer is over an object. For command buttons and menu items, the click event may also occur when the ENTER key is pressed while the object has the focus, or if a special key combination is pressed. These special key combinations are known as access key combinations.

To set an access key combination for an object, the caption property of the object must contain the & symbol. When this symbol appears, the letter after the & symbol will be underlined in the caption, and that letter, along with the ALT key, makes up the access key combination for the control.

For example, if we create a command button and set its caption to &START, that caption will appear on the command button as:

START

7

Page 9: Visual BASIC Notes

If, during run-time, the user presses ALT+S or ALT+s, the Click event for this button will occur, just as if the user had placed the mouse pointer over the button and clicked. Note that, just as with any other procedure, the Click procedure can be invoked from code by simply typing:

objectname_click

as a line of code.

The DblClick Event

The DblClick event occurs when the user presses and releases a mouse button twice in rapid succession while the mouse pointer is over an object. If the DblClick event does not occur within the system’s double-click time limit, the object will appear to have experienced two Click events.

Note: The Click and DblClick events do not distinguish between the left, right, and middle mouse buttons. If it is important to know which mouse buttons have been clicked, the MouseDown and MouseUp events may be used.

There are many other types of events, depending on the control object being discussed. During this short course, we will examine a number of these events.

III. Creating and Saving a Project

Project Files

Each time that you begin a new project, two files are created:

1. The Project File: This file has the name of the project, with the extension .VBP, and contains the information used by Visual Basic (and specified by the programmer) for building the project, such as the location of Visual Basics custom controls, the size of the project window, etc.

2. The Form File: This file has the name of the form, with the extension .FRM, and contains information concerning the form, including your code. This point is important, since you may occasionally create different projects that use a common form. Any modification made to that form will affect all projects using that form, if the form is saved with the same name.

Form files may be saved in ASCII or binary formats. The default file format is binary. To save the form and project files in ASCII format, click the SAVE AS TEXT checkbox.

8

Page 10: Visual BASIC Notes

Beginning a New Project

1. Start Visual Basic by double clicking its icon.

2. Select the File/New Project menu options.

Visual Basic will display a number of windows on the desktop, including:

i) A blank form with the caption Form 1.ii) The Project Window, which shows the forms, modules, and custom controls

included in the current project. The caption of the Project Window is the name of the current project, which by default is Project 1.

Note: If no Project Window is displayed, you can cause this window to appear by using the Window/Project menu options.

iii) The Properties Window, which shows the properties of the current object.

Note: If no Properties Window is displayed, you can cause this window to appear by using the Window/Project menu options.

In addition, the toolbox is displayed at the left side of the screen, and the menu bar is displayed at the top of the screen.

3. Save the new project using the File/Save Project As menu options. A “Save File As “ dialog box will appear with the query:

Save changes to Form1.frm?

Select the YES button. Choose a directory in which to save the project, and enter a name for the new form.

A “Save Project As” dialog box will appear. Enter the name for the .VBP file to be saved.

Note: Do not use the default .FRM and .VBP file names supplied by Visual Basic. Instead, save the .FRM and .MAK files with names that are descriptive of the project being designed.

Note: Each time you begin a new project, the AUTOLOAD.VBP file is loaded. This file causes a set of Visual Basic custom controls to be available to the user, and these controls (.VBX files) are shown in the project window. The programmer may modify the AUTOLOAD.VBP file so that more or fewer controls are loaded automatically upon new project creation. It is advisable, before modifying the AUTOLOAD.VBP file, to make a backup copy.

9

Page 11: Visual BASIC Notes

Exercise 1

Create and execute a simple application which displays one of three messages when a “display message” command button is clicked. Allow the user to end program execution when an “End” command button is clicked.

Procedure:

1. Start Visual Basic.

2. Select the File/New Project menu options.

3. Select the File/Save Project As menu options. Save the form as messages.frm and the make file as messages.mak.

4. Click the form to make sure that it is selected.

i) In the properties window, select the caption property. Change the caption of the form to:

Three Messages

ii) In the properties window, select the name property. Change the name of the form to:

frmmessages

4. On the toolbox, double click the command button icon. A new command button is created. Drag the command button to the lower right corner of the form.

5. Make sure that the properties window indicates the new command button.

i) Select the name property. Change the name of the command button to:

cmdend

ii) Select the caption property. Change the caption of the command button to:

&End

6. On the toolbox, double click the command button icon. A new command button is created. Drag the command button to the lower left corner of the form.

7. Make sure that the properties window indicates the new command button.

10

Page 12: Visual BASIC Notes

i) Select the name property and change it to:

cmddisplaynextmessage

ii) Select the caption property and change it to:

&Display Next Message

iii)Resize the command button so that the entire caption is displayed.

8. On the toolbox, double click the label icon (the icon with a capital A). A new label is created. Drag the new label to the top center of the form.

9. Make sure that the properties window indicates the new label.

i) Select the name property and change it to:

lblmessage

ii) Select the caption property and change it to blank.

iii)Resize the label so that its width is at least 3012, and its height is at least 492. You may use the mouse, or type these values into the height and width properties in the properties window.

iv)Set the border style property to:

1 - Fixed Single

by double clicking this property in the property window.

The visual implementation of this program is complete. Save the project before proceeding. The form should appear as shown in Figure 3.

11

Page 13: Visual BASIC Notes

Figure 3: The Three Messages Form

Now write the code for this application.

1. Double click any blank region of the form. The code window appears. Note that the code window may also be made visible by choosing the View/Code menu options.

2. Use the Object list box at the top of the code window to choose the General object. Make sure that the Procedure list box displays the Declarations procedure. The code for the General Declarations procedure is:

'all variables must be declaredOption Explicit

Dim messagecounter

The first line makes the comment that all variables must be declared.

The second line makes the comment true by issuing the Option Explicit Statement.

The third line declares the variable messagecounter as a variant. Since this variable is declared in the General Declarations area of the form, it is visible to all procedures in the form.

12

Page 14: Visual BASIC Notes

3. Use the object and procedure list boxes to go to the Form_Load procedure. Type in the Form_Load procedure code shown below.

Sub Form_Load ()lblmessage.Caption = "No messages"End Sub

This section of code is executed at application startup. It causes the caption of the lblmessage label to read “No messages”.

4. Use the object and procedure list boxes to go to the cmdend_click procedure. Type in the cmdend_click procedure code shown below.

Sub cmdend_Click ()BeepEndEnd Sub

When the Click event occurs on the cmdend command button object, the PC emits a beep, and then program execution terminates.

5. Now type in the code for the cmddisplaymessage command button Click procedure, shown below.

Sub cmddisplaymessage_Click ()ReDim message(3)

message(1) = "First message"message(2) = "Second message"message(3) = "Third message"

messagecounter = messagecounter + 1

If messagecounter > 3 Thenmessagecounter = 1End If

lblmessage.Caption = message(messagecounter)End Sub

The first line dimensions a local array called message() as a variant. When dimensioning arrays at the procedure level (as opposed to dimensioning them in the General Declarations code of the form, or in an external Basic Module), the REDIM statement must be used. This array will hold the three messages which will be displayed in the lblmessage label.

13

Page 15: Visual BASIC Notes

Next, messages 1, 2, and three are defined as “First message”, “Second message”, and “Third message”.

The next line increments the messagecounter variable, which is to be used as a subscript reference for the message() array.

The next three lines constitute a block-if statement. If the message counter has grown too large (i.e., if it is larger then three), then it is set back to 1 so that the first message may be repeated.

Finally, the message is displayed by setting the caption property of the lblmessage label equal to message(messagecounter).

Now run the program by choosing the Run/Start menu options. Note that you may give command buttons the focus by using either the mouse or the tab key. When a button has the focus, you may click the button using the enter key or the mouse. Note also that if a button does not have the focus, you may still execute its Click procedure by pressing the access key combination assigned to the button (ALT plus the underlined letter in the button’s caption).

You may exit the application using the cmdend command button, or by choosing the Run/End menu options.

14

Page 16: Visual BASIC Notes

Exercise 2

Create and execute an application that changes the color of the form randomly each time the form receives a Form_Click event. If the form receives a Form_DblClick event, set the background color of the form to bright white, and change the form’s caption to “White Form”. Allow the user to exit the program using a command button.

Procedure:

1. Start Visual Basic.

2. Select the File/New Project menu options.

3. Select the File/Save Project As menu options. Save the form as colors.frm and the make file as colors.mak.

4. Click the form to make sure that it is selected.

5. i) Change the form’s caption to:

The Colors Program

ii) Change the form’s name to:

frmcolors

6. Create a new command button by double clicking the command button icon in the toolbox.

7. i) Change the command button’s name to:

cmdend

ii) Change the command button’s caption to:

&End

The visual implementation phase of this project is now complete. Save the project. The form should appear as in Figure 4.

15

Page 17: Visual BASIC Notes

Figure 4: The Colors Form

Now begin the Code Generation phase of this project.

1. The cmdend_click procedure should contain the code:

Sub cmdend_Click ()EndEnd Sub

When the cmdend command button is clicked, program execution terminates.

2. The form_click procedure should contain the code:

Sub Form_Click ()Dim color 'declare the color variable

color = Int(16 * Rnd) 'find a random qbcolor number

frmcolors.BackColor = QBColor(color) 'set the form's background color 'equal to the random color we just 'generated

frmcolors.caption="The Colors Program"

End Sub

16

Page 18: Visual BASIC Notes

This code makes use of Visual Basic’s RND, INT , and QBCOLOR functions.

The line:Dim color

declares the variable color as a variant.

The line:

color=Int(16*Rnd)

sets the variable color equal to an integer value between 0 and 15. The RND keyword returns a decimal value between 0 and 1. If we multiply this value by 16, we have a real number between 0 and 16. The INT function returns the integer portion of its argument. The argument supplied to the INT function in this case is a real number between 0 and 16, so the function will return an integer between 0 and 15.

The QBCOLOR function sets a color based on its argument. Table II lists acceptable arguments for the QBCOLOR function, and the colors they represent.

Argument Color 0 Black 1 Blue 2 Green 3 Cyan 4 Red 5 Magenta 6 Yellow 7 White 8 Gray 9 Light Blue10 Light Green11 Light Cyan12 Light Red13 Light Magenta14 Light Yellow15 Bright White

Table II: QBCOLOR Arguments

Note: In Visual Basic, colors may also be set using the RGB function.

The line:

17

Page 19: Visual BASIC Notes

frmcolors.caption="The Colors Program"

sets the caption of the form to “The Colors Program”.

Finally, the line:

frmcolors.BackColor = QBColor(color)

sets the background color of the form to the color generated by the QBCOLOR statement.

3. The form_dblclick procedure should contain the code:

Sub Form_DblClick ()frmcolors.backcolor = QBColor(15) 'set the form's background color to bright whitefrmcolors.caption = "White Form" 'change the form's captionEnd Sub

When the form experiences a double-click event, its background color is set to QBCOLOR(15), bright white. At the same time, its caption is changed to “White Form”.

18

Page 20: Visual BASIC Notes

IV. Visual Basic Program Flow Control

General and Event Procedures

A general procedure is not associated with a particular object or event. Rather, it is a set of instructions that allow the application to perform a specific task, and must be invoked (called) from code. By contrast, an event procedure remains idle until the object the its code is associated with experiences the event referenced by the event procedure, or until the event procedure is invoked from code.

General procedures may be placed either in form code or in a Basic module. General procedures which are placed in a form may be accessed only from within that form. This is why variables declared in the General Declarations area of a form are not visible outside that form. General procedures placed in a module may be accessed from within any form or module in the project.

The use of general procedures helps compartmentalize complex code into easily understandable segments.

Note: Visual Basic also supports the use of functions. Functions return values, and are referenced in the same way as variables. Procedures do not return values. Visual Basic also supports the use of methods. Methods work similarly to procedures and functions, but are specific to the object which supports them. For example, the form supports a number of graphics methods. These methods are specifically designed functions used to draw on the form.

Event procedures are created for the programmer at the time of creation of the control object with which they are associated. General procedures must be created by the programmer during design-time.

To create a general procedure:

1. Open the code window for the form or module which is to contain the general procedure.

2. Select the View/New Procedure menu options.

3. In the text box, type a name for the new general procedure.

4. Select the SUB option button if you wish to create a procedure. Select the FUNCTION option button to create a function.

5. Choose O.K.

The new procedure has been created, and code may be entered into its template. In the code window, the new procedure may be found by choosing General in the object list box, and by choosing the correct procedure name in the Procedure list box.

19

Page 21: Visual BASIC Notes

Note: Procedures are called from code by typing their name. If arguments are to be passed to a procedure, the name or value of each argument should follow the name of the procedure being called. Arguments in this list should be separated by commas. Arguments passed to functions, on the other hand, must be enclosed in parentheses.

Visual Basic supports the use of the CALL keyword, but this word is optional. If the CALL keyword is used, the argument list should be enclosed in parentheses.

Example: Suppose that we have created a general procedure named stepit. The code for the stepit procedure is given below.

sub stepit(x,y,z)x = x + 1y = y + 1z = z + 1End Sub

Suppose that we have a command button named cmdmove, and that when this button is clicked, we want to call the stepit procedure, and pass it an x value of 2, a y value of 4, and a z value of 6. The code of the cmdmove_click procedure might look like this:

Sub cmdmove_clickstepit 2,4,6End Sub

The following code is equivalent:

Sub cmdmove_clickCALL stepit(2,4,6)End Sub

20

Page 22: Visual BASIC Notes

The code shown below is also equivalent:

Sub cmdmove_clickDIM sendxvalueDIM sendyvalueDIM sendzvalue

sendxvalue = 2sendyvalue = 4sendzvalue = 6

stepit sendxvalue,sendyvalue,sendzvalue

End Sub

In each of the three cases shown above, the stepit sub procedure is invoked, and reads in the first argument passed to it as its local variable x, the second passed argument as the local variable y, and the third argument passed as the local variable z.

The Option Explicit Statement

While developing complex applications, confusion can arise due to mis-spelled variable names and the re-use of the same variable name locally in several procedures. Much of this confusion can be avoided by the use of the Option Explicit statement in the General Declarations procedure.

The Option Explicit statement forces the declaration of all variables, both local and global. The Option Explicit statement, if used, must appear in the General Declarations procedure.

Example: The General Declarations procedure shown below uses the Option Explicit statement.

'all variables must be declaredOption Explicit

Declaring Global Variables

If only a single form is used in a project, then variables declared using a DIM statement in the General Declarations procedure of that form may be considered to be global, since those variables are visible to all procedures associated with the form.

If more than one form exists in a project, then variables that must be visible to procedures in all forms, (i.e., variables that are to be global to the project), must be declared in a Basic Module using the GLOBAL statement.

21

Page 23: Visual BASIC Notes

To create a Basic Module:

1. Make the Project window active.

2. Select the File/New Module menu options.

3. Select the File/Save File As menu options, and save the file with the desired name and a .BAS extension.

At this point, the new Basic Module has been added to your project, and should appear in the project window. Variables defined in the declarations section of an external module using the GLOBAL statement are visible to all procedures in all forms of a project. The syntax of the GLOBAL statement is:

GLOBAL variablename, variablename, ...,variablename

You may also define arrays using the GLOBAL statement, and specify Visual Basic data types. A sample global type declaration is shown below.

GLOBAL myinteger AS INTEGER

Declaring Local Variables

Variables declared in form or module procedures other than the General Declarations procedure are, by default, local. These variables are visible only within the procedure where they are declared. This allows the programmer to use the same variable name in multiple procedures without fear of confusion or incorrect variable values.

Variables may be declared using the DIM or STATIC statements. These statements may also be used with the keyword AS to define a variable type (integer, string, etc.).

Variables declared with the DIM statement are reinitialized to zero each time the procedure is executed. Variables declared with the STATIC statement retain their values from one procedure execution to the next.

Arrays may be declared locally within a procedure. To declare a local array, the REDIM statement must be used. The use of the DIM statement to declare an array in a procedure other than the Global Declarations procedure causes Visual Basic to report an error at program startup.

22

Page 24: Visual BASIC Notes

V. Flow Control Statements

IF-THEN Statements

The Visual Basic IF-THEN statement has the same structure as the QuickBasic IF-THEN statement. This statement uses the value of an expression to control the order in which program statements are executed.

The IF-THEN statement tests the equivalence of two expressions. These comparisons can be combined using the logical operators AND, OR, and NOT. One difference between the QuickBasic IF-THEN statement and the Visual Basic IF-THEN statement is this: The Visual Basic IF-THEN statement can make use of the IS comparator.

The syntax of the IF-THEN statement can take one of two forms:

1. The single line IF-THEN statement:

IF expression AND expression OR expression THEN true ELSE false

where: expression = a comparison of two values that yields TRUE or FALSE

true = the action to be taken if the expression(s) is TRUEfalse = the action to be taken if the expression(s) is FALSE

Examples:

i) IF x = y THEN GOTO skiptherest

If it is true that x is equal to y, then go to the line labeled skiptherest

ii) IF (x+2) <> (y/5) THEN z = z + 1 ELSE z = 0

If it is true that x + 2 is not equal to y/5, then add 1 to z. If x + 2 is equal to y/5, then set z equal to 0.

iii) IF x = 1 AND y >= 3 THEN cmdstart_click

If both expressions are TRUE (i.e., if x equals 1 and y is greater than or equal to 3), then execute the cmdstart_click event procedure.

iv) IF x < 4 OR x = y THEN cmdstart_dblclick

If either expression is TRUE (i.e., if x is less than 4 or if x is equal to y) then execute the cmdstart_dblclick procedure.

v) IF x AND y THEN EXIT SUB

23

Page 25: Visual BASIC Notes

If both x and y are non-zero, then exit the procedure currently being executed.

vi) IF NOT x THEN EXIT SUB

If x is a non-zero number, then exit the procedure currently being executed.

2. The Block IF-THEN statement:

IF expression1 THEN

truestatements1

ELSEIF expression2 THEN

truestatements2

.

.

.

ELSE

falsestmnts

END IF

where: expression1 = a comparison of two values that yields TRUE or FALSE

expression2 = a comparison of two values that yields TRUE or FALSE

true1 = A set of statements to be executed only if expression1 yields TRUE

true2 = A set of statements to be executed only if expression2 yields TRUE

falsestmnts = A set of statements to be executed only if none of the expressions in the IF or ELSEIF lines of

the block IF yields TRUE

Expressions can be combined in the IF and ELSEIF lines of the block IF statement using AND’s, OR’s, and NOT’s, just as they can with the single line version of the IF then statement.

Example:

24

Page 26: Visual BASIC Notes

IF x = 1 AND y <> x THEN

x = x + 2

ELSEIF x = 1 OR y < 10 THEN

x = x + 3

ELSEIF x = 5 THEN

z = 0

ELSE

a = 3

END IF

The block IF statement above is equivalent to the set of single line IF-THEN statements shown below.

IF x = 1 AND y <> x THEN x = x + 2IF x = 1 OR y < 10 THEN x = x + 3IF x = 5 THEN z = 0IF x <> 1 AND x <> 5 AND y >= 10 THEN a = 3

Notes:1. Each block IF statement must possess an END IF. If for some reason an END IF

statement is omitted, you will often see errors such as “Block IF without END IF” or “NEXT without FOR”.

2. In both cases (single line and block syntax), AND’s, OR’s, NOT’s, ELSE’s and ELSEIF’s are optional.

3. It is permissible to nest block IF-THEN statements.

IF x = y THENIF x > 5 THENz = z + 1END IF

END IF

In the example shown, z is incremented by 1 only if x = y and x > 5

25

Page 27: Visual BASIC Notes

4. Comparisons must be made between like variable types (i.e., numeric to numeric or string to string). It is not permissible to compare a string variable to a numeric variable. This is a particularly important point to note when working with variant data types, which may contain either numeric or string variables. The ISNUMERIC function is useful when working with variant data types.

The ISNUMERIC Function

The ISNUMERIC function returns a value indicating whether or not a variant variable can be converted to a numeric data type. The syntax of the ISNUMERIC function is:

ISNUMERIC(variant)

If the variant can be converted to a numeric data type (i.e., if the variable contains a number), the ISNUMERIC function returns TRUE (i.e., 1).

If the variant cannot be converted to a numeric data type (i.e., if the variable contains a string), the ISNUMERIC function returns a FALSE (i.e., 0). Some related functions of interest to the programmer are:

i) ISDATEii) ISEMPTYiii)ISNULLiv)The VARTYPE Function

Example: Consider the following code fragment.

Sub cmdstart_clickDIM whatami

whatami = “I’m a string”

IF ISNUMERIC(whatami) THENtxtwhatheis.text = “He’s a number”ELSEtxtwhatheis.text = “He’s a string”END IF

End Sub

The result of the execution of this code is that the message “He’s a string” will be displayed in the text box named txtwhatheis.

Example: Consider the following code fragment.

26

Page 28: Visual BASIC Notes

Sub cmdstart_clickDIM whatami

whatami = 5

IF ISNUMERIC(whatami) THENtxtwhatheis.text = “He’s a number”ELSEtxtwhatheis.text = “He’s a string”END IF

End Sub

The result of the execution of this code is that the message “He’s a number” will be displayed in the text box named txtwhatheis.

The SELECT CASE Statement

The SELECT CASE statement is analogous to the CASE statement in Pascal, or the switch statement in C. The syntax of the SELECT CASE statement is:

SELECT CASE expressionCASE comparison1,comparison2

statements1CASE comparison3,comparison4

statements2CASE ELSE

statements3END SELECT

where: expression = the variable being compared. This value must be a constant, not a TRUE or FALSE value

comparisoni = a constant expressionstatements1 = a set of statements to be executed if expression = comparison1 OR

expression = comparison2statements2 = a set of statements to be executed if expression = comparison3 OR

expression = comparison4statements3 = a set of statements to be executed if no comparison is true.

Example: Consider the code fragment below.

SELECT CASE menunumber

27

Page 29: Visual BASIC Notes

CASE 1addcustomers

CASE 2addtransactions

END SELECT

If menunumber is equal to 1, then the addcustomers procedure is executed. If menunumber equals 2, then the addtransactions procedure is executed.

Example: Consider the code fragment below.

SELECT CASE userinput$

CASE “Y”, ”y”doit

CASE “N”, “n”Exit Sub

END SELECT

If the string userinput$ is equal to “Y” or equal to “y” then the doit procedure is executed. If userinput$ is equal to “N” or “n” then the current procedure is exited.

Note: Comparison expressions can be ranges using the TO keyword.

FOR-NEXT Loops

FOR-NEXT loops are used to repeat a group of instructions some specified number of times. The syntax for the FOR-NEXT loop is:

FOR counter = start TO end STEP increment

statement block

NEXT counter

where: counter = a variable used as the loop counter. It is not permissible to use array elements as loop counters.

end = the final value for counter

28

Page 30: Visual BASIC Notes

increment = the amount by which the counter is incremented each time that the loop executes

statement = a group of statements that is executed each time that the loopblock executes

Note: The STEP keyword is optional. If no STEP is specified, then increment defaults to 1.

The FOR-NEXT loop begins with the FOR statement. Program execution continues downward until the NEXT statement is encountered. When the NEXT statement is encountered, increment is added to counter, and an evaluation of counter is made.

When increment is positive, execution branches back to the FOR statement if counter<=end.

When increment is negative, execution branches back to the FOR statement if counter>=end.

If the evaluation fails, program execution continues with the statement following NEXT.

Notes:

1. Changing the value of counter while inside a loop makes the program difficult to debug, and may cause unexpected results.

2. FOR-NEXT loops may be nested.

Example: Consider the code fragment below.

FOR x = 1 to 5FOR y = 6 to 2 STEP -1txtshownumber.text = STR$(y)NEXT y

NEXT x

This code fragment causes the text box txtshownumber to display, (in this order), the numbers65432

This process is repeated 5 times.

Note: The text property of a text box must contain a string value. Since y may be numeric (depending on how it was declared), the STR$ function, which converts numbers to strings, was used.

The EXIT FOR Statement

29

Page 31: Visual BASIC Notes

When the EXIT FOR statement is executed, control is transferred to the statement following the NEXT statement. EXIT FOR exits only the current FOR-NEXT loop. When the EXIT FOR statement is executed within a nested FOR-NEXT loop, control is transferred to the loop that is one nested level above the current loop.

DO-WHILE and DO-UNTIL Loops

The DO-LOOP statement repeats the execution of a block of statements WHILE or UNTIL an exit condition is met. The syntax of the DO-LOOP is:

DO WHILE expressionstatementsLOOP

or

DO UNTIL expressionstatementsLOOP

or

DOstatementsLOOP WHILE expression

or

DO statementsLOOP UNTIL expression

where: expression = an expression that evaluates to TRUE or FALSEstatements = a block of statements to be executed WHILE or UNTIL expression

is TRUE

Example: Consider the code fragment below.

x = 0DO WHILE x < 10x = x + 1LOOP

30

Page 32: Visual BASIC Notes

The loop will be executed 10 times, with x being incremented by 1 upon each execution.

The EXIT DO Statement

The EXIT DO statement transfers control to the statement following the LOOP statement. When used within nested DO-LOOP statements, EXIT DO transfers control to the loop that is one nested level above the current loop.

The EXIT SUB Statement

The EXIT SUB statement immediately exits the procedure in which it appears.

The EXIT FUNCTION Statement

The EXIT FUNCTION statement is used to exit a function, and is analogous to the EXIT SUB statement.

VI. Visual Basic User Input

In a Visual Basic application, the user can provide input by means of Message Boxes, Text Boxes, and Input Boxes.

Message Boxes

The programmer can cause a message box to be displayed using either the MSGBOX statement or the MSGBOX function. The MSGBOX function returns a value indicating which button was pushed by the user to clear the message box. The MSGBOX statement simply displays a message, but does not return a value.

Message boxes are generated during run-time by statements in code.

Function Syntax:

variable = MsgBox (msg,type,title)

Statement Syntax:

MsgBox msg,type,title

where: msg = the message to be displayed. This can be a string or variant variable, or a string enclosed in quotes.

31

Page 33: Visual BASIC Notes

type = a numeric expression that is the sum of the values specifying the number and type of buttons to display, the icon style to use, and the modality of the

message boxtitle = A string to be displayed in the title bar of the message box

Table III lists the values that may be summed to arrive at a message box type.

Value Meaning0 Display OK button only1 Display OK and Cancel buttons2 Display Abort, Retry, and Ignore buttons3 Display Yes, No, and Cancel buttons4 Display Yes and No buttons5 Display Retry and Cancel buttons16 Use the STOP icon32 Use the Questionmark icon64 Use the exclamation point icon0 Application modal

4096 System modal

Table III: Message Box Constants

Note: The modality of the message box determines which actions can be taken by the user while the message box is displayed. An application modal message box allows the user to operate in applications other than the application displaying the message box. The application displaying the message box is “frozen” until the user clears the message box by pushing a button.

A system modal message box forces the user to respond to the message box before any action can be taken in any application.

Table IV lists the values returned by the msgbox function.

Value Meaning1 OK button selected2 Cancel button selected

32

Page 34: Visual BASIC Notes

3 Abort button selected4 Retry button selected5 Ignore button selected6 Yes button selected7 No button selected

Table IV: Values Returned by the MsgBox Function

Input Boxes

An Input Box displays to the user a dialog box with a message, a text box, an OK button and a Cancel button. The user may type inside the text box and then close the dialog box by clicking either button.

If the OK button was clicked, the Input Box returns the contents of the text box. If the Cancel button was clicked, the Input Box returns null (i.e., “”, a zero length string).

Input Boxes are generated during run-time by statements in code. The syntax for displaying an Input Box is:

variable = InputBox (prompt, title, default, xpos, ypos)

where: variable = The variable into which the user’s response is to be placed.prompt = A string expression displayed in the dialog box as a message.

This may be a string or variant variable, or an expression enclosed in quotes.

title = A string expression or string/variant variable to be displayed in the title bar of the dialog box.

default = A string expression or string/variant variable to be displayed in the text box as the default response.

xpos = The location, in twips, of the left edge of the dialog box.ypos = The location, in twips, of the top edge of the dialog box.

Note: Title, default, xpos, and ypos are optional.

Text Boxes

Text boxes are control objects created during design-time, as opposed to Input Boxes and Message Boxes, which are generated during run-time by statements in code. Text boxes are rectangular areas where text is displayed. Text may be inserted into a text box either during run-

33

Page 35: Visual BASIC Notes

time or during design-time by altering the TEXT property of the text box. In effect, the TEXT property of the text box may be treated as a variable. It may be read, manipulated, and changed.

Note: Visual Basic refuses to place text in a text box using center alignment unless the MultiLine property of the text box is set to TRUE.

34

Page 36: Visual BASIC Notes

Exercise 3

Write a program that allows the user to enter numbers into two text boxes. If the user enters a non-numeric value into either text box, force the user to re-enter that number. Once the user has completed entry, display a message box that states which text box contained the greater number, and clear the text from each text box. The user should be able to exit the program using a command button.

Procedure:

1. Create a project. Save the make file as compare.mak and the form file as compare.frm.

2. Change the form’s caption to:

The Comparison Program

and its name to:

frmcompare

3. Create a text box, and place it in the upper left corner of the form (the text box icon in the tool box has the letters ab displayed). Change the text box name to txtleft and its text property to “” (a null string).

4. Create a text box, and place it in the upper right corner of the form. Name the text box txtright, and change its text property to “” (a null string).

5. Create a command button, and place it in the lower left corner of the form. Name the command button cmdcompare, and change its caption to &Compare.

6. Create a command button, and place it in the lower right corner of the form. Name the command button cmdexit, and change its caption to &Exit.

The visual implementation of the program is complete. Save the project before continuing. The form should appear as shown in Figure 5.

35

Page 37: Visual BASIC Notes

Figure 5: The Compare Form

Now write the code for the Compare program. The General Declarations procedure should contain the code:

'All variables must be declaredOption Explicit

The cmdcompare_click procedure should contain the code:

Sub cmdcompare_Click ()Dim leftvalueDim rightvalue

If Not IsNumeric(txtleft.text) Then 'if the left text box doesn't contain a numberMsgBox txtleft.text + " Is Not Numeric. Please Re-Enter.", , "Warning - Left Text Box" 'ask the user to re-enterExit Sub 'don't compare valuesEnd If

If Not IsNumeric(txtright.text) Then 'if the right text box doesn't contain a numberMsgBox txtright.text + " Is Not Numeric. Please Re-Enter.", , "Warning - Right Text Box" 'ask the user to re-enterExit Sub 'don't compareEnd If

'if we have gotten this far, both values must be numeric, so we can compare them

leftvalue = Val(txtleft.text) 'convert the text in the txtleft text box to a number and store in leftvaluerightvalue = Val(txtright.text) 'convert the text in the txtright text box to a number and store in rightvalue

(Continued on next page)

36

Page 38: Visual BASIC Notes

If leftvalue > rightvalue ThenMsgBox "The Left Text Box Value Was Greater", , "Comparison Result" 'tell the user that the left value was greaterElseIf rightvalue > leftvalue ThenMsgBox "The Right Text Box Value Was Greater", , "Comparison Result" 'tell the user that the right value was greaterElse 'the two values must be equalMsgBox "The Two Values Are Equal", , "Comparison Result" 'so tell the userEnd If

txtleft.text = "" 'clear the left text boxtxtright.text = "" 'clear the right text box

End Sub

The cmdexit_click procedure should contain the code:

Sub cmdexit_Click ()EndEnd Sub

Note the use of the VAL function, which converts string values into numeric values.

37

Page 39: Visual BASIC Notes

Exercise 4

Write a program that gets the user’s name and a date using the Input Box function and displays this data in the caption of the form. The user should be able to exit the program using a command button.

Procedure:

1. Create a new project. Save the make file as name.mak and the form file as name.frm.

2. Change the form’s caption to:

The Name and Date Program

and its name to:

frmnameanddate

3. Create a command button and place it in the lower left corner of the form. Name the command button cmdask, and change its caption to &Ask.

4. Create a command button and place it in the lower right corner of the form. Name the command button cmdexit, and change its caption to &Exit.

The visual implementation of the program is complete. Save the project before continuing. The form should appear as shown in Figure 6.

Figure 6: The ASK Form

38

Page 40: Visual BASIC Notes

Now generate the code of the name program. The General Declarations procedure should contain the code:

'All variables must be declaredOption Explicit

The cmdexit_click procedure should contain the code:

Sub cmdexit_Click ()EndEnd Sub

The cmdask_click procedure should contain the code:

Sub cmdask_Click ()Dim usernameDim responsedate

asknameagain:username = InputBox("Please Enter Your Name", "Query: Name") 'get the user's name, and store it in

‘usernameIf IsNumeric(username) Then GoTo asknameagain 'if the user responded with a number, ask

‘for the name again

askdateagain:responsedate = InputBox("Please Enter a Date", "Query: Date") 'get a date from the userIf Not IsDate(responsedate) Then GoTo askdateagain 'if the response was not a date, then ask for

‘the date again

frmnameanddate.Caption = username + " " + responsedate 'change the caption of the form to display ‘the name and date

End Sub

39

Page 41: Visual BASIC Notes

VII. The Mouse Device

In order to take full advantage of the Windows environment, applications should allow the user full access to the use of the mouse. Mouse events are generated by mouse clicks, mouse movement, and the combination of mouse clicks and keyboard presses. Click and DblClick events can be mouse generated. In addition to these two events, several other events can be initiated with the mouse, including the MouseDown, MouseUp, and MouseMove events.

The MouseDown Event

This event occurs when the user presses a mouse button. The syntax of the MouseDown event procedure declaration is:

Sub MouseDown (Button as Integer, Shift as Integer, X as Single, Y as Single)

A list of the arguments used by the MouseDown event is presented in Table V.

Argument Description

Button The button was pressed to cause this event. The Button argument may have values of:1: The left mouse button was pressed2: The right mouse button was pressed4: The middle mouse button was pressed

Shift This argument indicates the state of the Shift, Alt, and Ctrl keys at the time the MouseDown event occurred. The Shift argument may have values of:1: The Shift key was depressed 2: The Ctrl key was depressed4: The Alt key was depressedx: The sum of the values for multiple keys depressedExample: Shift = 6 indicates that both the Ctrl and Alt keys were depressed.

X, Y The current location of the mouse pointer at the time that the MouseDown event occurred, expressed in terms of the form coordinate system.

Table V: MouseDown Event Procedure Arguments

The MouseUp Event

40

Page 42: Visual BASIC Notes

This event occurs when the user releases a mouse button. The syntax of the MouseDown event procedure declaration is:

Sub MouseUp (Button as Integer, Shift as Integer, X as Single, Y as Single)

The MouseUp arguments are the same as those for the MouseDown event procedure, listed in Table V.

The MouseMove Event

This event occurs when the user moves the mouse pointer across an object. The syntax of the MouseDown event procedure declaration is:

Sub MouseMove (Button as Integer, Shift as Integer, X as Single, Y as Single)

The arguments for this procedure are the same as those listed in Table V.

The MouseMove event is generated continuously as the mouse pointer moves across objects. Objects receive the MouseMove event when the mouse pointer is within their borders.

The Form Coordinate System

The coordinates for a form may be specified using a number of different types of units. The units used are defined by the ScaleMode property of the form. The default unit is the twip.

1 inch = 1440 twips

The ScaleMode property may also be set to:

Points: 1 inch = 72 PointsPixels: The number of pixels per inch is a function of monitor resolutionInchesMillimetersCentimeters

The origin for the form coordinate system is defined by the ScaleTop and ScaleLeft form properties. The default values assigned by Visual Basic for these properties are:

(ScaleLeft, ScaleTop) = (0,0)

so the upper left corner of the form is at (0,0). Note that the form, in this context, is taken to mean the form’s usable area, exclusive of the borders and title bar.

The CurrentX and CurrentY Properties

41

Page 43: Visual BASIC Notes

These properties determine the horizontal and vertical coordinates for the next printing or graphics method. These properties are not available at design-time.

VIII. Menu Design

Menu bars can be included in the Visual Basic application. Menu items are control objects, and can experience Click events. To create a menu item, follow the procedure given below.

1. Click the form to ensure that it is selected.

2. Choose the Window/Menu Design menu options.

3. The menu design window will be displayed. At its top, the menu control properties dialog box is visible. At its bottom, the menu control list box can be seen.

4. To add a menu item, type in a caption, and a menu item name. It is good programming practice to start each menu item name with the letters:

mnu

Example: If we create a menu item with the caption &File, we might assign it the name mnufile.

At the top of the menu item list box, right and left arrow buttons are displayed. These buttons are used to create a menu hierarchy. Menu items fall into two classes:

Menu Titles: These items usually do not have attached code, but rather serve as a “door” which allows the user access to a group of menu items. For example, we might create a menu title with the caption &File.

Menu Titles appear left aligned in the menu item list box. When creating a menu title, use the right arrow button to place the object in the correct position in the menu hierarchy.

Menu Items: These items have attached code in their Click procedures. If we create a menu title &File, we might create under it a number of menu items with captions such as &Open, &Close, &Print, and &Exit, each of which executes some code when clicked.

Menu items appear right aligned in the menu item list box, and their names are preceded in the list box by periods (...). When creating a menu item, use the right arrow button to place the object in the correct position in the menu hierarchy.

Example: Suppose that we wish to create a menu bar with two menu titles, File and Edit. Under the File menu title, we wish to place the Open, Close, and Exit menu items. Under the Edit menu title, we wish to place the Cut, Copy, and Paste menu items.

42

Page 44: Visual BASIC Notes

When menu design is complete, the menu control list box should appear as in Figure 7.

Figure 7: A Menu Design Window

Figure 8 shows the form with the menu just designed. The File menu is expanded so that its menu items are visible.

43

Page 45: Visual BASIC Notes

Figure 8: The File Menu

Code can be written into the Click procedure for a menu item just as for any other control.

IX. Graphic Controls

Visual Basic provides the programmer with several built in graphic controls, including:

1. The Line Control2. The Shape Control3. The Picture Control4. The Image Control

The Line Control

The line is a graphic control displayed as a horizontal, vertical, or diagonal line. This control can be used at design-time to draw lines on forms, or during run-time instead of, or in addition to, the line method. Lines drawn on a form will remain on the form even if the AutoRedraw property of that form is FALSE. Line controls may also be displayed in picture boxes and frames.

The start and stop points for the line control are specified by setting its X1,Y1, X2, and Y2 properties.

44

Page 46: Visual BASIC Notes

The Shape Control

The shape is a graphic control displayed on the form, and may be used instead of or in addition to the circle and line methods. Depending on the setting of the shape control’s SHAPE property, this control may appear as a rectangle, square, oval, circle, rounded rectangle, or rounded square. Table VI lists the settings and meanings for the shape control’s SHAPE property.

Setting Description0 (Default) Rectangle1 Square2 Oval3 Circle4 Rounded Rectangle5 Rounded Square

Table VI: The Shape Control’s Shape Property Settings

Image Controls

This control can be used to display a picture. The image control uses fewer resources and repaints more quickly than a picture box, but many of the properties possessed by the picture box are not possessed by the image control. However, the image control does support the STRETCH property. When set to TRUE, this property causes any file loaded into the image control to automatically stretch to fill the control.

Picture Box Controls

These controls can be used to display bitmaps, icons, or metafiles.

Note: To cause a picture box to automatically resize to display an entire graphic, set the control’s AutoSize property to TRUE.

The MOVE Method

This method moves a form or control. The syntax for the MOVE method is:

objectname.MOVE left, top, width, height

where: left = the new horizontal coordinate for the left edge of the objecttop = the new vertical coordinate for the top edge of the objectwidth = the new width of the objectheight = the new height of the object

Note: Only the left argument is required. All other arguments are optional.

45

Page 47: Visual BASIC Notes

Exercise 5

Write a program that continuously tracks mouse position over the form, and displays the current x and y coordinates of the mouse in two text boxes (one for the x coordinate, and one for the y). If the user clicks the form, a shape should be inserted in the form at the current mouse location. The type of shape should be based on a menu selection. The user should be able to exit the program by means of a menu selection.

Procedure:

1. Create a new project. Save the form file as tracker.frm, and save the make file as tracker.mak.

2. Create two text boxes. Place them, one above the other, in the upper left corner of the form. Name the top one txtx, and the bottom one txty. Cause their captions to be zero length stings.

3. Create a menu title named mnufile with a caption of &File. Under it, create a menu item named mnuexit, with a caption of &Exit.

4. Create a menu title named mnushape with a caption of &Shape. Under it, create the following menu items:

Name Captionmnurectangle &Rectanglemnusquare &Squaremnuoval &Ovalmnucircle C&irclemnuroundedrectangle Rounded R&ectanglemnuroundedsquare Rounded S&quare

When you are finished, the menu design window should appear as shown in Figure 9.

46

Page 48: Visual BASIC Notes

Figure 9: Tracker’s Menu Construction

5. Create two labels, and size them as shown if Figure 10. Name one label lblx, and give it a caption of X coordinate. Place this label above the txtx text box. Name the other label lbly, and give it a caption of Y coordinate. Place this label above the txty text box.

6. Create a shape control and name it shpinsert. Set the shapes visible property to FALSE.

The visual implementation of the program is complete. Save the project. The completed form should appear as in Figure 10.

47

Page 49: Visual BASIC Notes

Figure 10: The Tracker Form

Now generate the code for this project. The General Declarations procedure should contain the code:

'all variables must be declaredOption Explicit

Dim shapeflag ‘this is the variable that tells us which shape to drop into the formDim insertx ‘this is the variable that tells us the mouse pointer’s current x positionDim inserty ‘this is the variable that tells us the mouse pointer’s current y position

48

Page 50: Visual BASIC Notes

The form_mousemove procedure should contain the code:

Sub Form_MouseMove (Button As Integer, Shift As Integer, x As Single, y As Single)

txtx.text = x ‘update x coordinate displaytxty.text = y ‘update y coordinate displayinsertx=x ‘make the x coordinate visible to all proceduresinserty=y ‘make the y coordinate visible to all proceduresEnd Sub

The mnuexit_click procedure should contain the code:

Sub mnuexit_Click ()EndEnd Sub

The mnucircle_click procedure should contain the code:

Sub mnucircle_Click ()shapeflag = 3 ‘set the shapeflag for circleEnd Sub

The mnuoval_click procedure should contain the code:

Sub mnuoval_Click ()shapeflag = 2 ‘set the shapeflag for ovalEnd Sub

The mnurectangle_click procedure should contain the code:

Sub mnurectangle_Click ()shapeflag = 0 ‘set the shapeflag for rectangleEnd Sub

The mnuroundedrectangle_click procedure should contain the code:

Sub mnuroundedrectangle_Click ()shapeflag = 4 ‘set the shapeflag for rounded rectangleEnd Sub

The mnuroundedsquare_click procedure should contain the code:

Sub mnuroundedsquare_Click ()shapeflag = 5 ‘set the shapeflag for rounded squareEnd Sub

49

Page 51: Visual BASIC Notes

The mnusquare_click procedure should contain the code:

Sub mnusquare_Click ()shapeflag = 1 ‘set the shapeflag for squareEnd Sub

The form_click procedure should contain the code:

Sub Form_Click ()shpinsert.Shape = shapeflag 'set the shape property to the user selected valueshpinsert.Left = insertx 'set the left edge of the shape at the current x coordinateshpinsert.Top = inserty 'set the top edge of the shape at the current y coordinateshpinsert.Visible = True 'make the shape visible

End Sub

The form_dblclick procedure should contain the code:

Sub Form_DblClick ()shpinsert.Visible = False 'clear the formEnd Sub

The code generation phase of this project is complete. Run the program.

50

Page 52: Visual BASIC Notes

X. Debugging

Visual Basic provides a number of debugging tools. Some of these tools are described in the following sections.

The Debug Window

The Debug window is automatically opened at run-time when an application is launched from Visual Basic. The Debug window can be used to execute individual lines of code (for example, you may print the values of variables from the Debug window). You may not use the Debug window unless program execution has been temporarily halted by breaking the program. You may break program execution by hitting the CTRL+BREAK keys, or by choosing the run/break menu options. Once program execution has been broken, it may be resumed using the run/continue or run/restart menu options.

Watch expressions are also displayed in the Debug window.

The Add Watch Command

This command is accessed using the debug/add watch menu options. When this command is issued, a dialog box is displayed into which the programmer may enter a watch expression. This expression may be any valid Visual Basic expression such as:

thisvariablethisvariable <= thatvariable(thisvariable+thatvariable)=theothervariable

etc.

The status of the watch expression is continuously displayed during run-time in the Debug window. The Add Watch command gives the programmer the options of:

Watch Expression: Simply display the value or status of the expression.

Break When Expression is True: Temporarily halt program execution when the expression becomes true.

Break When Expression Has Changed: Temporarily halt program execution when the value of a variable has changed, or when the status of an expression has toggled from true to false or from false to true.

The Edit Watch Command

51

Page 53: Visual BASIC Notes

This command is accessed using the debug/edit watch menu options. Using this command, watch expressions may be edited, added, and deleted.

The Toggle Breakpoint Command

This command is accessed using the debug/toggle breakpoint menu options. When a breakpoint is toggled on a particular line of code, program execution is broken if that line of code is reached.

To toggle a breakpoint on a line of code, place the cursor anywhere on that line, and then choose the debug/toggle breakpoint menu options. The line of code will be highlighted to inform the programmer that the line of code has been toggled. To clear the breakpoint from the line of code, place the cursor in the line, then choose the debug/toggle breakpoint menu options. The highlighting on the line of code will disappear.

To remove all breakpoints from a program, choose the debug/clear all breakpoints menu options.

Note: Breakpoints are not saved with the program.

The Single Step Command

This command is accessed using the debug/single step menu options, or by pressing F8. When program execution has been broken, the programmer may step through the program one line at a time.

The Procedure Step Command

This command is accessed using the debug/procedure step menu options. This command treats Sub and Function procedures as a single executable statement. Using this command, the programmer (once program execution has been broken) can step through program execution one procedure at a time.

The ON ERROR GOTO Statement

The ON ERROR statement allows the programmer to trap and handle errors that may occur during run-time. If the ON ERROR statement is not used, any error that occurs during run-time is fatal, and terminates program execution.

The syntax for the ON ERROR statement is:

ON ERROR GOTO linelabel

Example:

52

Page 54: Visual BASIC Notes

Say that we have a code fragment where the user has just entered values for two variables x and y. We want to set z = x / y, but we are concerned about a division by zero error. We might trap this error in the following way:

ON ERROR GOTO errorocurred ‘if we get an error, trap itz = x / y

EXIT SUB

errorocurred:MSGBOX “An error has ocurred. Please make sure that y <> 0”,,”Warning”EXIT SUB

END SUB

The RESUME and RESUME NEXT Statements

The RESUME and RESUME NEXT statements may be placed in an error handling routine such as the one beginning with the line label “errorocurred” in the example above. The RESUME statement causes program execution to continue starting at the line where the error ocurred. The RESUME NEXT statement causes program execution to continue starting at the statement following the program line where the error ocurred.

XI. Graphics Methods

Using graphics methods, the programmer can, from code, “draw” on an object. The two objects most commonly drawn on using graphics methods are the form and the printer. There are a number of graphics methods available to the programmer, including:

1. The Points Method2. The Line Method3. The Circle Method4. The CLS Method

The POINT Method

53

Page 55: Visual BASIC Notes

The point method is used to draw points on the form (or some other object). The syntax for the point method is:

objectname.POINT (x, y)

where: x = the horizontal coordinate of the point to be drawny = the vertical coordinate of the point to be drawn

Note: Objectname is optional. The default value for objectname is the current form. If the point referred to by x and and y is outside the object, the point method returns -1.

The LINE Method

The line method draws a line on the form (or some other object). The syntax for the line method is:

objectname.LINE (x1, y1) - (x2, y2), color, B, F

where: (x1, y1) = the starting point for the line(x2, y2) = the ending point for the linecolor = the color for the line (using RGB or QBCOLOR)B = draws a box with upper left corner at (x1, y1) and lower right

corner at (x2, y2)F = causes the box to be filled (solid). The F argument can only be

used in conjunction with the B argument

Notes:1. Objectname is optional. The default value for objectname is the current form. All other

arguments except (x1, y1) and (x2, y2) are optional as well.

2. When a line is drawn, CurrentX and CurrentY are set to the endpoint of the line.

3. Optional arguments may be omitted from the line statement, but their places must be held by commas.

The CLS Method

The cls method clears text or graphics generated during run-time from a form (or some other object). The syntax for the cls method is:

objectname.CLS

When the cls method is executed, CurrentX and CurrentY are set to zero. The CIRCLE Method

54

Page 56: Visual BASIC Notes

The circle method draws a circle on the form (or some other object). The syntax for the circle method is:

objectname.circle (x, y), radius, color, start, end, aspect

where: (x, y) = the coordinates of the center of the circleradius = the radius of the circlecolor = the color of the circle (using RGB or QBCOLOR)start = the starting angle for an arc (in radians)end = the ending angle for an arc (in radians)aspect = the aspect ratio (height/width) for the circle. An aspect ratio of one causes

a true circle to be drawn. Aspect ratios other than one cause ellipses to be drawn.

Notes:

1. Only the (x,y) and radius arguments are required.

2. When drawing an arc or ellipse segment, if start is negative, the circle method will draw a radius to start, and will treat the angle to positive.

3. When the circle method is executed, CurrentX and CurrentY are set to the center point of the circle specified.

4. Optional arguments may be omitted from the circle statement, but their places must be held by commas.

XII. The Grid Control

The Grid Control provides the programmer with an easy method for creating and displaying tables (rows and columns) of information during run-time. Note that the intersection of a row and column is referred to as a cell.

In order to use the Grid Control, the GRID.VBX file must appear in the project window during design-time. If the GRID.VBX file does not appear in the project window it may be added by following the procedure listed below:

1. Select the project window.

55

Page 57: Visual BASIC Notes

2. Choose the File/Add File menu options.

3. Select the file to be added (in this case, GRID.VBX).

4. Press the OK button.

The ROW and COL properties of the Grid Control specify the current cell. The current cell can be specified by setting these properties in code, or the user can select a cell using the mouse or arrow keys on the keyboard. The Grid Control’s TEXT property refers to the contents of the current cell.

The Grid Control’s ROWS and COLS properties refer to the size of the grid in rows and columns. A grid can possess no more than 2000 rows and 400 columns.

The AddItem Method

The AddItem method can be used to add a new row to a Grid Control during run-time. The syntax of the AddItem method is:

objectname.AddItem item, index

where: objectname = the name of the grid control to which the new row is to be added.

item = a string expression to add to the control. Use the tab character (chr$(09)) to separate multiple strings to be inserted into each column of a new row.

index = an integer representing the position within the control where the new row is to be placed. Note that to place a new row in the first row position of a grid, set index = 0.

The RemoveItem Method

The RemoveItem method is used to remove a row from a grid control. The syntax for the RemoveItem Method is:

objectname.RemoveItem index

56

Page 58: Visual BASIC Notes

where: objectname = the name of the grid control from which the row is to be removed.index = the number of the row to be removed (first row has index = 0).

XIII. Keyboard Events

Three events are associated with keyboard activity during run-time. These are; the KeyDown event, the KeyUp event, and the KeyPress event. Objects can experience keyboard events only if they have the focus (i.e., their border or title bar is highlighted, etc.). Forms can have the focus only if it has no visible or highlighted controls. However, if the form’s KeyPreview property is set to TRUE, the form will receive keyboard events before any other object.

The KeyDown Event

This event occurs when a key is pressed. The syntax for the KeyDown event is:

Sub objectname_KeyDown (Keycode as Integer, Shift as Integer)

where: objectname = the name of the object being referencedKeycode = a code corresponding to the key that was pressedShift = a code corresponding to the state of the ALT, CTRL, and SHIFT

keys

The KeyUp Event

This event occurs when a key is released, for the object which has the focus. The syntax for the KeyUp event is:

Sub objectname_KeyUp (Keycode as Integer, Shift as Integer)

Objectname, Keycode, and Shift have the same meanings as those for the KeyDown event.

The possible values for the Shift argument in both the KeyDown and KeyUp events are listed in Table VII.

Shift Value ALT Status CTRL Status SHIFT Status0 Not Pressed Not Pressed Not Pressed1 Not Pressed Not Pressed Pressed2 Not Pressed Pressed Not Pressed3 Not Pressed Pressed Pressed4 Pressed Not Pressed Not Pressed

57

Page 59: Visual BASIC Notes

5 Pressed Not Pressed Pressed6 Pressed Pressed Not Pressed7 Pressed Pressed Pressed

Table VII: Values for the KeyDown, KeyUp Shift Argument

Note that the value of the Shift argument is:

0 if SHIFT, ALT, and CTRL are all not pressed1 if the SHIFT key only is pressed2 if the CTRL key only is pressed4 if the ALT key is pressed

The value of the Shift argument is the sum of the values of the keys which are currently pressed. For example, if the SHIFT and ALT keys are pressed, the value of the Shift argument is 1 + 4 = 5.

The value of the Keycode argument for the KeyDown and KeyUp events corresponds to the values listed in the Visual Basic CONSTANT.TXT file.

The KeyPress Event

The KeyPress event occurs when the user presses a key with an ASCII code. The syntax for the KeyPress event is:

Sub objectname_KeyPress (KeyAscii As Integer)

where: objectname = the name of the object receiving the key strokeKeyAscii = the ASCII key code for the key that was pressed

Note: The ASCII code for the key combination CTRL+@ is zero. Because Visual Basic recognizes a KeyAscii value of zero as a null (zero length) string, it is good practice to avoid using CTRL+@ in a Visual Basic application.

XIV. The Timer Control

The timer control can be used to execute code at regular intervals by causing a timer event. The Timer’s interval property is set at design-time to the amount of time (in milliseconds) to wait between each execution of the timer’s timer event.

58

Page 60: Visual BASIC Notes

Example: If we wished to display “Hello” in a text box named txthello every 1/2 second, we could create a timer named tmrhello, and set its interval property to 500. In the timer event procedure for tmrhello, we could type:

txthello.text = “Hello”

59

Page 61: Visual BASIC Notes

Exercise 6

Write a program that inserts variable width lines at random orientations every 0.5 seconds when a “Start” command button is clicked, and continues line insertion until a “Stop” command button is clicked. The user should be able to clear the screen using a menu selection. Using a second menu selection, the user should be able to draw horizontal lines, the width of which is controlled by a scroll bar.

Procedure:

1. Create a new Visual Basic project. Save the form file as lines.frm, and save the make file as lines.mak.

2. Name the form frmlines, and set its caption to The Lines Program.

3. Create a command button named cmdstart, with a caption &Start. Place the command button in the lower left corner of the form.

4. Create a command button named cmdstop with a caption S&top. Place the command button in the lower right corner of the form.

5. Create a menu title named mnufile, with a caption File. Under this menu title, create a menu item named mnuend, with a caption of End.

6. Create a menu title named mnuscreen, with a caption of Screen. Under this menu title, create a menu item named mnuclear with a caption Clear. Also create a menu item named mnuhorizontal, with a caption Horizontal Lines.

7. Create a timer (by double clicking the stopwatch icon in the toolbox) named tmrdraw. Set the timer’s interval property to 500 milliseconds.

8. Create a horizontal scroll bar named hsblinewidth. Place the scroll bar between the Start and Stop command buttons. Size the scroll bar as shown in Figure 11. Set the scroll bars MIN property to 1, and its MAX property to 15.

9. Create a label named lbllinewidth. Set its caption to Horizontal Line Width, and size and place it as shown in Figure 11.

10. Create a label named lblwidthdisplay. Set its caption to a null string. Size and place it as shown in Figure 11.

The visual implementation of this project is complete. Save the project. The completed form should appear as shown in Figure 11.

60

Page 62: Visual BASIC Notes

Figure 11: The Lines Form

Now begin the code generation phase of the project. The General Declarations procedure should contain the code:

'all variables must be declaredOption Explicit

Dim startflag 'make the startflag visible to all procedures in this form

The cmdstart_click procedure should contain the code:

Sub cmdstart_Click ()startflag = 1 - startflag 'toggle the startflag between zero and oneEnd Sub

The cmdstop_click procedure should contain the code:

Sub cmdstop_Click ()startflag = 0 'turn the startflag offEnd Sub

The form_load procedure should contain the code:

61

Page 63: Visual BASIC Notes

Sub Form_Load ()lblwidthdisplay.Caption = "Default" 'initialize the caption of the lblwidthdisplay label so

'that it is not blank at startupEnd Sub

The hsblinewidth_change procedure should contain the code:

Sub hsblinewidth_Change ()lblwidthdisplay.Caption = hsblinewidth.Value 'update the lblwidthdisplay label to reflect

'the current value of the horizontal scroll barEnd Sub

The mnuclear_click procedure should contain the code:

Sub mnuclear_Click ()frmlines.Cls 'clear the form

End Sub

The mnuend_click procedure should contain the code:

Sub mnuend_Click ()EndEnd Sub

The mnuhorizontal_click procedure should contain the code:

Sub mnuhorizontal_Click ()Dim xstart 'declare the line's starting x coordinateDim y 'declare both lines' y coordinateDim xend 'declare the line's ending x coordinate

frmlines.DrawWidth = hsblinewidth.Value 'set the drawwidth property of the form to 'the value indicated by the hsblinewidth 'horizontal scroll bar so that lines drawn 'have the correct width

xstart = frmlines.ScaleWidth * Rnd 'pick a random x starting coordinate between 'zero and the width of the form

(continued on next page)y = frmlines.ScaleHeight * Rnd 'pick a random y coordinate between zero 'and the height of the form

62

Page 64: Visual BASIC Notes

xend = frmlines.ScaleWidth * Rnd 'pick a random x ending coordinate between 'zero and the width of the form

frmlines.Line (xstart, y)-(xend, y) 'draw the line

End Sub

The tmrdraw_timer procedure should contain the code:

Sub tmrdraw_Timer ()Dim xstart 'declare the starting x coordinate 'for the randomly oriented linesDim ystart 'declare the starting y coordinate for 'the randomly oriented linesDim xend 'declare the ending x coordinate for 'the randomly oriented linesDim yend 'declare the ending y coordinate for 'the randomly oriented lines

If startflag <> 1 Then Exit Sub 'if the startflag is not on, then don't draw

frmlines.DrawWidth = 1 + Int(15 * Rnd) 'set the drawwidth property of the form to 'a number between 1 and 15 so that we can 'draw various width linesxstart = frmlines.ScaleWidth * Rnd 'set the starting x coordinate to a value 'between 0 and the width of the form

ystart = frmlines.ScaleHeight * Rnd 'set the starting y coordinate to a value 'between 0 and the height of the form

xend = frmlines.ScaleWidth * Rnd 'set the ending x coordinate to a value 'between 0 and the width of the form

yend = frmlines.ScaleHeight * Rnd 'set the ending y coordinate to a value 'between 0 and the height of the form

frmlines.Line (xstart, ystart)-(xend, yend) 'draw the line

End Sub

Note: During run-time, minimize the form, then restore it. Now change the form’s AutoRedraw property to TRUE, and try this again. Note the difference in the way the application behaves during run-time.

63

Page 65: Visual BASIC Notes

Exercise 7

Write a program that allows the user to fill a grid with part numbers, part prices, and in-stock part quantities.

Procedure:

1. Create a new project. Save the form file as parts.frm, and the make file as parts.mak.

2. Create a grid named grdinventory. Set the grids COLS property to 3, and its ROWS property to 10. Place the grid top-center on the form. Note that the FIXEDROWS property is set to 1. This gives us one title (fixed) row at the top of the grid. Set the FIXEDCOLS property to 0. We do not need any fixed columns.

3. Create a menu title named mnufile with a caption of File. Under this title, create a menu item named mnuend, with a caption of End.

The visual implementation of this project is complete. Save the project. The completed form should appear as shown in Figure 12.

Figure 12: The Parts Form

64

Page 66: Visual BASIC Notes

Now begin the code generation phase of the project.

The General Declarations procedure should contain the code:

‘all variables must be declaredOption Explicit

The form_load procedure should contain the code:

Sub Form_Load ()Dim colcounter

grdinventory.Row = 0 'set the current row to zerogrdinventory.Col = 0 'set the current column to zerogrdinventory.Text = "Part Number" 'place text in current cellgrdinventory.Col = 1 'set the current column to 1grdinventory.Text = "Price" 'place text in the current cellgrdinventory.Col = 2 'set the current column to 2grdinventory.Text = "Quantity in Stock" 'place text in the current cell

For colcounter = 0 To 2 'step through the columnsgrdinventory.ColWidth(colcounter) = 1300 'widen the columnNext colcounter

End Sub

The grdinventory_click procedure should contain the code:

Sub grdinventory_click ()Dim response

'ask the user what to put into the selected cellresponse = InputBox("Enter Text to Place in Cell", "Cell Entry")

'place the user's response in the current cellgrdinventory.Text = response

End Sub

The grdinventory_keydown procedure should contain the code:

65

Page 67: Visual BASIC Notes

Sub grdinventory_KeyDown (keycode As Integer, Shift As Integer)

If keycode = &HD Then 'the enter key was pressedgrdinventory_click 'act as if a cell had been clickedEnd If

End Sub

The mnuend_click procedure should contain the code:

Sub mnuend_Click ()EndEnd Sub

The code generation phase of this project is now complete. Run the application.

66

Page 68: Visual BASIC Notes

XV. The File-System Controls

These controls include the Directory List Box, the File List Box, and the Drive List Box.

The Drive List Box

With this box, the user can select disk drives during run-time.

The Directory List Box

With this box, the user can select directories and paths during run-time.

The File List Box

With this box, the user can select files during run-time.

In a typical application, these three controls are used in combination. A sample program making use of the File-System controls is given in Appendix A.

XVI. ASCII and Binary File I/O

There are three ways to access files using Visual Basic:

1. Sequential Access2. Binary Access3. Random Access

We will discuss Binary and Sequential Access.

Sequential Access Files

A sequential file contains ASCII data, and can be opened in one of three ways:

1. For output.2. For input.3. For append.

The syntax for opening a sequential file is:

OPEN filename FOR mode AS # filenumber

where: filename = the path and name of the file to openmode = input, output, or appendfilenumber = the device number assigned to the file (an integer between 1

and 255, inclusive)

67

Page 69: Visual BASIC Notes

Notes:

1. The FREEFILE function returns the value of the first un-used file number.

2. The APPEND mode sets the file pointer to the end of the file so that new records may be “tacked on”.

3. Opening a file in OUTPUT mode destroys the current contents of the file.

4. Once a file is opened, it must always be closed. To close a file, use the statement:

CLOSE #filenumber

Example: Suppose that we want to create a file containing the words

YournameMynameHisnameHername

We could make use of the following code fragment.

OPEN “c:\temp\names.dat” FOR OUTPUT as #1PRINT #1, “Myname”PRINT #1, “Yourname”PRINT #1, “Hisname”PRINT #1, “Hername”CLOSE #1

The file created would have the appearance:

YournameMynameHisnameHername

If we later wished to read this file into an array, we could use the following code fragment.

68

Page 70: Visual BASIC Notes

DIM namesarray(4)DIM namecounter

OPEN “c:\temp\names.dat” FOR INPUT AS #1FOR namecounter =1 to 4

IF EOF(1) THEN EXIT FORINPUT #1, namesarray(namecounter)NEXT namecounterCLOSE #1

Binary Access Files

A binary file contains binary data, and is opened with the statement:

OPEN filename FOR BINARY AS #filenumber

To write data into a binary file, use the statement:

PUT #filenumber, bytelocation,contents

where: filenumber = the device number assigned to the filebytelocation = the byte location in the file at which writing is to begincontents = the information or variable to be written into the file

To read from a binary file, use the statement:

GET #filenumber, bytelocation,variablename

where: filenumber = the device number assigned to the filebytelocation = the byte location within the file at which reading is to beginvariablename = the name of the variable in which the read information is to be

stored

69

Page 71: Visual BASIC Notes

Exercise 8

Write a program that monitors the keyboard and displays any ASCII key pressed (in character form) in one text box and its ASCII code in another text box.

Procedure:

1. Create a new project. Save the form file as keys.frm, and the make file as keys.mak.

2. Create a text box named txtcharacter. Set its text property to null. Position the text box in the upper left corner of the form.

3. Create a text box named txtcode. Set its text property to null, and position it in the upper right corner of the form.

4. Create a label named lblcharacter. Set its caption to “Character”, and position it above the txtcharacter text box.

5. Create a label named lblcode. Set its caption to “ASCII Code” and position it above the txtcode text box.

6. Set the KeyPreview property of the form to TRUE. Set the Caption property of the form to “The Keys Program”. Set the name property of the form to frmkeys.

7. Create a command button named cmdend. Set its caption to &End, and position it in the lower right corner of the form.

The visual implementation of the project is complete. Save the project. The completed form should appear as in Figure 13.

70

Page 72: Visual BASIC Notes

Figure 13: The Keys Form

Now begin the code generation phase of the project. The General Declarations procedure should contain the code:

‘all variables must be declaredOption Explicit

The cmdend_click procedure should contain the code:

Sub cmdend_Click ()EndEnd Sub

The form_KeyPress procedure should contain the code:

71

Page 73: Visual BASIC Notes

Sub Form_KeyPress (keyascii As Integer)

txtcharacter.Text = Chr$(keyascii) 'convert the keyascii code into a character 'and display that character in the txtcharacter 'text box

txtcode.Text = keyascii 'display the ASCII code in the txtcode text boxEnd Sub

The txtcharacter_change procedure should contain the code:

Sub txtcharacter_Change ()'don't let the character be displayed twice'in case the user is typing in the text boxtxtcharacter.Text = Right$(txtcharacter.Text, 1)End Sub

The code generation phase is complete. Run the program.

72

Page 74: Visual BASIC Notes

Exercise 9

Write a program that acts as a mini-database for names and phone numbers. Create a distribution disk for this program.

Procedure:

1. Create a new project. Save the form file as phones.frm and the make file as phones.mak.

2. Name the form frmphone, and set its caption property to “The Phone Number Program”.

3. Create a menu title named mnufile with a caption of File. Under this menu title, create a menu item named mnuopen with the caption Open. Also create a menu item named mnusave, with the caption Save. Finally, create a menu item named mnuend with the caption End.

4. Create a grid control with two columns and twenty rows. Cause the grid to have one fixed row and no fixed columns. Name the grid grdphone.

5. Create a menu title named mnugrid and caption Grid. Under this menu title, create a menu item named mnuaddrow and captioned Add Row. Also create a menu item named mnudeleterow and captioned Delete Row.

The visual implementation of the project is complete. Save the project. The completed form should appear as in Figure 14.

73

Page 75: Visual BASIC Notes

Figure 14: The Phones Form

Now begin the code generation phase of the project. The General Declarations procedure should contain the code:

'all variables must be declaredOption Explicit

Dim currentfile 'make the currentfile variable 'visible to all procedures in the 'form

74

Page 76: Visual BASIC Notes

The form_load procedure should contain the code:

Sub Form_Load ()grdphone.Row = 0 'set the current row to zerogrdphone.Col = 0 'set the current column to zerogrdphone.Text = "Name" 'fill the current cellgrdphone.ColWidth(0) = 3000 'set the width of column zero wide, 'so that it can hold long namesgrdphone.Col = 1 'set the current column to 1grdphone.Text = "Phone" 'fill the current cellgrdphone.ColWidth(1) = 1500 'make column 1 wide enough to hold 'phone numbers

currentfile = "c:\temp\phone.dat" 'set the currentfile variable to some 'default file nameEnd Sub

The mnuaddrow_click procedure should contain the code:

Sub mnuaddrow_Click ()'add a row to the form at the current locationgrdphone.AddItem "", grdphone.SelStartRow

End Sub

The mnudeleterow_click procedure should contain the code:

Sub mnudeleterow_Click ()'delete a row from the grid at the current locationgrdphone.RemoveItem grdphone.SelStartRowEnd Sub

The mnuend_click procedure should contain the code:

Sub mnuend_Click ()EndEnd Sub

The mnuopen_click procedure should contain the code:

75

Page 77: Visual BASIC Notes

Sub mnuopen_Click ()Dim filetogetDim nameofpersonDim phoneDim gridrowDim rowcounterDim colcounterfiletoget = InputBox("Enter the name of the file to open", "Filename", currentfile) 'get a filenameIf filetoget = "" Then Exit Sub 'if the user hit the

‘cancel button, then go no furthercurrentfile = filetoget 'set the currentfile variable to the filename that we are about to load

On Error GoTo cantopenit 'if an error occurs, go to the error handling routineOpen filetoget For Input As #1 'open the fileDo While Not EOF(1) 'if we reach the end of the file, exit this loopInput #1, nameofperson 'input a nameInput #1, phone 'input a phone numbergridrow = gridrow + 1 'increment the gridrow counter If gridrow > (grdphone.Rows - 1) Then 'if we have exceeded the capacity of the grid grdphone.AddItem "", gridrow 'add a row to the grid End Ifgrdphone.Col = 0 'set the current column to zerogrdphone.Row = gridrow 'set the current row to gridrowgrdphone.Text = nameofperson 'place the name in the gridgrdphone.Col = 1 'set the current column to onegrdphone.Text = phone 'place the phone number into the gridLoop 'loop until we reach the end of the fileClose #1 'close the file

For rowcounter = gridrow + 1 To grdphone.Rows - 1 'go through any un-used grid rowsFor colcounter = 0 To 1 'and columnsgrdphone.Row = rowcounter 'set the current row to rowcountergrdphone.Col = colcounter 'set the current column to colcountergrdphone.Text = "" 'empty the current cellNext colcounterNext rowcounter

Exit Sub 'end the procedure if no errors occurredcantopenit: 'start of error handling routineMsgBox "Cannot Open File", , "Warning" 'tell the user that an error occurredExit Sub 'end the procedure

End Sub

76

Page 78: Visual BASIC Notes

The mnusave_click procedure should contain the code:

Sub mnusave_Click ()Dim filetosaveDim rowcounterDim colcounter

'get a filename from the userfiletosave = InputBox("Enter Filename to Save", "Save File", currentfile)If filetosave = "" Then Exit Sub 'if the user hit the cancel button 'go no further

currentfile = filetosave 'set the currentfile variable to the filename 'that we are savingOn Error GoTo cantsaveit 'if an error occurs, go to the error handling routine

Open filetosave For Output As #1 'open the fileFor rowcounter = 1 To grdphone.Rows - 1 'step through each rowFor colcounter = 0 To 1 'and columngrdphone.Row = rowcounter 'set the current row equal to rowcountergrdphone.Col = colcounter 'set the current column equal to colcounterPrint #1, grdphone.Text 'print the current cell's contents to the fileNext colcounterNext rowcounterClose #1 'close the fileExit Sub 'if no errors occurred, end the procedure

cantsaveit: 'start of error handling routineMsgBox "Cannot Save File", , "Warning" 'tell the user that an error occurredExit Sub 'end the procedureEnd Sub

The code generation phase of the project is complete. Run the application.

To create the distribution disk for this application:

1. Start Visual Basic’s SetupWizard by double clicking its icon.

i) The SetupWizard will build the application’s executable file. This can also be accomplished by choosing the File/Make EXE File menu options in Visual Basic.

ii) The SetupWizard will compress all needed files and assign them to a disk layout.

iii)You will be notified of the number of blank formatted diskettes needed.

2. Use the Select Project File button to browse for your application’s make file.

77

Page 79: Visual BASIC Notes

3. Choose the Next button to continue.

4. Select any features needed by your application, and choose the Next button to continue.

5. Inform the SetupWizard of the disk drive and disk type to use when creating master distribution disks. Hit the Next button.

6. Use the Add Files button to add any special files required by your application, such as bitmaps, INI files, etc. Hit the Next button.

7. The SetupWizard will create the master distribution disks.

78

Page 80: Visual BASIC Notes

Appendix A

A Sample Application Making Use of the File-System Controls

79

Page 81: Visual BASIC Notes

The Form File

VERSION 2.00Begin Form frmsize Caption = "The Size Program" ClientHeight = 3600 ClientLeft = 876 ClientTop = 1524 ClientWidth = 7800 Height = 4020 Left = 828 LinkTopic = "Form1" ScaleHeight = 3600 ScaleWidth = 7800 Top = 1152 Width = 7896 Begin CommandButton cmdcancel Cancel = -1 'True Caption = "Cancel" Height = 495 Left = 6360 TabIndex = 11 Top = 1200 Width = 1215 End Begin DriveListBox drvdrive Height = 288 Left = 3240 TabIndex = 10 Top = 3120 Width = 2775 End Begin CommandButton cmdok Caption = "OK" Default = -1 'True Height = 495 Left = 6360 TabIndex = 8 Top = 480 Width = 1215 End

80

Page 82: Visual BASIC Notes

Begin DirListBox dirdirectory Height = 1752 Left = 3240 TabIndex = 7 Top = 840 Width = 2775 End Begin ComboBox cbofiletype Height = 288 Left = 240 Style = 2 'Dropdown List TabIndex = 4 Top = 3120 Width = 2655 End Begin FileListBox filfiles Height = 1752 Left = 240 TabIndex = 2 Top = 840 Width = 2655 End Begin TextBox txtfilename Height = 375 Left = 240 TabIndex = 0 Top = 360 Width = 2655 End Begin Label lbldrive Caption = "Drive:" Height = 255 Left = 3240 TabIndex = 9 Top = 2880 Width = 1095 End Begin Label lbldirname Height = 255 Left = 3360 TabIndex = 6 Top = 480 Width = 1215 End Begin Label lbldirectories Caption = "Directories"

81

Page 83: Visual BASIC Notes

Height = 255 Left = 3360 TabIndex = 5 Top = 240 Width = 1215 End Begin Label lblfiletype Caption = "File Type:" Height = 255 Left = 240 TabIndex = 3 Top = 2880 Width = 1095 End Begin Label lblfilename Caption = "Filename" Height = 255 Left = 240 TabIndex = 1 Top = 120 Width = 1095 EndEnd

82

Page 84: Visual BASIC Notes

Code

General Declarations

'all variables must be declaredOption Explicit

Sub cbofiletype_Click ()'change the pattern of the file list box'according to the file type that the user'selectedSelect Case cbofiletype.ListIndexCase 0filfiles.Pattern = "*.*"Case 1filfiles.Pattern = "*.txt"Case 2filfiles.Pattern = "*.doc"Case 3filfiles.Pattern = "*.bas"End Select

End Sub

Sub cmdcancel_Click ()EndEnd Sub

83

Page 85: Visual BASIC Notes

Sub cmdok_Click ()Dim pathandname As StringDim filesize As StringDim Path

' if no file is selected then tell the user and'exit this procedureIf txtfilename.Text = "" ThenMsgBox "You must first select a file"Exit SubEnd If'make sure that path ends with backslashIf Right$(filfiles.Path, 1) <> "\" ThenPath = filfiles.Path + "\"ElsePath = filfiles.PathEnd If

'extract the path and name of the selected fileIf txtfilename.Text = filfiles.FileName Thenpathandname = Path + filfiles.FileNameElsepathandname = txtfilenameEnd If

'the next statement may cause an error so we'set an error trapOn Error GoTo filelenerror

'get the file size of the filefilesize = Str$(FileLen(pathandname))

'display the size of the fileMsgBox "The size of " + pathandname + " is " + filesize + " bytes"

Exit Sub

filelenerror:'there was an error, so display error message and'exitMsgBox "Cannot find size of " + pathandname, 48, "Error"Exit Sub

End Sub

Sub dirdirectory_Change ()

84

Page 86: Visual BASIC Notes

'a directory was just selected by the user so'update the path of the file list box'accordinglyfilfiles.Path = dirdirectory.Path

'also update the lbldirname labellbldirname.Caption = dirdirectory.Path

End Sub

Sub drvdrive_Change ()'the next statement may cause an error so we'set error trap.On Error GoTo driveerror

'change the path of the directory list box to'the new drivedirdirectory.Path = drvdrive.DriveExit Sub

driveerror:'an error occurred so tell the user and'restore the original drive.MsgBox "Drive Error", 48, "Error"Exit Sub

End Sub

Sub filfiles_Click ()'update the txtfilename text box with the file'name selectedtxtfilename.Text = filfiles.FileNameEnd Sub

Sub filfiles_DblClick ()'update the txtfilename text box'with the file name that was just double clickedtxtfilename.Text = filfiles.FileName

'execute the cmdok_click() procedurecmdok_Click

End SubSub Form_Load ()'fill the cbofiletype combo box.

85

Page 87: Visual BASIC Notes

cbofiletype.AddItem "All files (*.*)"cbofiletype.AddItem "Text files (*.txt)"cbofiletype.AddItem "Doc Files (*.doc)"cbofiletype.AddItem "Basic Files (*.bas)"'initialize the cbofiletype combo box to'item #0 (i.e., all files)cbofiletype.ListIndex = 0

'update the lbldirnamelabel with the pathlbldirname.Caption = dirdirectory.Path

End Sub

86

Page 88: Visual BASIC Notes

The Make File

SIZE.FRMC:\VB\GRID.VBXC:\WINDOWS\SYSTEM\MSOLE2.VBXC:\WINDOWS\SYSTEM\ANIBUTON.VBXC:\WINDOWS\SYSTEM\CMDIALOG.VBXC:\WINDOWS\SYSTEM\CRYSTAL.VBXC:\WINDOWS\SYSTEM\GAUGE.VBXC:\WINDOWS\SYSTEM\GRAPH.VBXC:\WINDOWS\SYSTEM\KEYSTAT.VBXC:\WINDOWS\SYSTEM\MSCOMM.VBXC:\WINDOWS\SYSTEM\MSMASKED.VBXC:\WINDOWS\SYSTEM\MSOUTLIN.VBXC:\WINDOWS\SYSTEM\PICCLIP.VBXC:\WINDOWS\SYSTEM\SPIN.VBXC:\WINDOWS\SYSTEM\THREED.VBXProjWinSize=152,402,248,215ProjWinShow=2IconForm="frmsize"

87

Page 89: Visual BASIC Notes

Appendix BVisual Basic Derived Mathematical Functions

88

Page 90: Visual BASIC Notes

Function Visual Basic EquivalentSecant sec(x) = 1 / cos(x)Cosecant cosec(x) = 1 / sin(x)Cotangent cotan(x) = 1 / tan(x)Inverse Sine arcsin(x) = atn(x / sqr( -x * x + 1)Inverse Cosine arccos(x) = atn(-x / sqr(-x * x + 1)) +1.5708Inverse Secant arcsec(x) = atn(x / sqr(x * x - 1)) + sgn(sgn(x) - 1) * 1.5708Inverse Cosecant arccosec(x) = atn(x / sqr(x * x - 1)) + (sgn(x) - 1)*1.5708Inverse Cotangent arccotan(x)=atn(x) + 1.5708Hyperbolic Sine hsin(x) = (exp(x) - exp(-x)) / 2Hyperbolic Cosine hcos(x) = (exp(x) + exp(-x)) / 2Hyperbolic Tangent htan(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))Hyperbolic Secant hsec(x) = 2 / (exp(x) + exp(-x))Hyperbolic Cosecant hcosec(x) = 2 / (exp(x) - exp(-x))Hyperbolic Cotangent hcotan(x) = (exp(x) + exp(-x)) / (exp(x) - exp(-x))Inv. Hyperbolic Sine harcsin(x) = log(x + sqr(x * x + 1))Inv. Hyperbolic Cosine harccos(x) = log(x + sqr(x * x - 1))Inv. Hyperbolic Tangent harctan(x) = log((1 + x) / (1 - x)) / 2Inv. Hyperbolic Secant harcsec(x) = log((sqr(-x * x + 1) + 1) / x)Inv. Hyperbolic Cosecant harccosec(x) = log((sgn(x) * sqr(x * x + 1) + 1) / x)Inv.Hyperbolic Cotangent

harccotan(x) = log((x + 1) / (x - 1)) / 2

Logarithm log base n (x) = log(x) / log (n)

89