• No results found

Visual BASIC Notes

N/A
N/A
Protected

Academic year: 2021

Share "Visual BASIC Notes"

Copied!
88
0
0

Loading.... (view fulltext now)

Full text

(1)

Fundamentals of Visual Basic

U.E. Callaway Plant

Course Notes

(2)

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.

(3)

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 Box Text Box Command Button Radio Button Label Frame Check Box Combo Box Hor. Scroll Bar Timer

List Box Ver. Scroll Bar Drive List Box Dir. List Box

File 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.

(4)

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 Button

opt - Option Button

chk - Check Box

mnu - Menu Item

dir - Directory List Box

fil - File List Box

drv - Drive List Box

lbl - Label

frm - Frame

lst - List Box

frm - 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.

(5)

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. The data types supported by Visual Basic are shown in Table I.

(6)

Data Type Suffix Storage Size Range

Integer % 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 input

IF 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.

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:

(7)

startflag=1-startflag ‘toggle the startflag variable between zero and one END 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.

(8)

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:

(9)

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.

(10)

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.

(11)

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. i) Select the name property and change it to:

(12)

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.

(13)

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 declared Option 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.

(14)

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 () Beep

End End 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 Then messagecounter = 1 End 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.

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

(15)

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.

(16)

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.

(17)

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 () End

End 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

(18)

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 Blue 10 Light Green 11 Light Cyan 12 Light Red 13 Light Magenta 14 Light Yellow 15 Bright White

Table II: QBCOLOR Arguments

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

The line:

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

(19)

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 white frmcolors.caption = "White Form" 'change the form's caption

End 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”.

(20)

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.

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

(21)

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 + 1 y = y + 1 z = z + 1 End 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_click stepit 2,4,6

End Sub

The following code is equivalent: Sub cmdmove_click

CALL stepit(2,4,6) End Sub

The code shown below is also equivalent: Sub cmdmove_click

(22)

DIM sendyvalue DIM sendzvalue sendxvalue = 2 sendyvalue = 4 sendzvalue = 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 declared Option 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.

To create a Basic Module:

1. Make the Project window active.

(23)

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.

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.

(24)

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 TRUE

false = 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

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.

(25)

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: 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

(26)

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 + 2 IF x = 1 OR y < 10 THEN x = x + 3 IF x = 5 THEN z = 0

IF 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 THEN

IF x > 5 THEN z = z + 1 END IF END IF

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

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).

(27)

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) ISDATE ii) ISEMPTY iii)ISNULL

iv)The VARTYPE Function

Example: Consider the following code fragment. Sub cmdstart_click

DIM whatami

whatami = “I’m a string”

IF ISNUMERIC(whatami) THEN txtwhatheis.text = “He’s a number” ELSE

txtwhatheis.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. Sub cmdstart_click

DIM whatami whatami = 5

IF ISNUMERIC(whatami) THEN txtwhatheis.text = “He’s a number” ELSE

txtwhatheis.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.

(28)

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 expression

CASE comparison1,comparison2 statements1 CASE comparison3,comparison4 statements2 CASE ELSE statements3 END SELECT

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

TRUE or FALSE value

comparisoni = a constant expression

statements1 = a set of statements to be executed if expression = comparison1 OR

expression = comparison2

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

expression = comparison4

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

Example: Consider the code fragment below. SELECT CASE menunumber

CASE 1 addcustomers CASE 2

addtransactions 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

(29)

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

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 loop

block 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.

(30)

2. FOR-NEXT loops may be nested.

Example: Consider the code fragment below. FOR x = 1 to 5

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

NEXT x

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

5 4 3 2 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

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 expression statements LOOP or DO UNTIL expression statements LOOP or DO

(31)

statements

LOOP WHILE expression or

DO

statements

LOOP UNTIL expression

where: expression = an expression that evaluates to TRUE or FALSE

statements = a block of statements to be executed WHILE or UNTIL expression is TRUE

Example: Consider the code fragment below. x = 0

DO WHILE x < 10 x = x + 1

LOOP

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.

(32)

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.

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 box

title = 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 Meaning

0 Display OK button only

1 Display OK and Cancel buttons

2 Display Abort, Retry, and Ignore buttons

3 Display Yes, No, and Cancel buttons

4 Display Yes and No buttons

5 Display Retry and Cancel buttons

16 Use the STOP icon

32 Use the Questionmark icon

64 Use the exclamation point icon

0 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.

(33)

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 Meaning

1 OK button selected

2 Cancel button selected

3 Abort button selected

4 Retry button selected

5 Ignore button selected

6 Yes button selected

7 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.

(34)

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-time or during design-run-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

(35)

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.

(36)

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 declared Option Explicit

The cmdcompare_click procedure should contain the code:

Sub cmdcompare_Click () Dim leftvalue

Dim rightvalue

If Not IsNumeric(txtleft.text) Then 'if the left text box doesn't contain a number MsgBox txtleft.text + " Is Not Numeric. Please Re-Enter.", , "Warning - Left Text Box" 'ask the user to re-enter

Exit Sub 'don't compare values End If

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

Exit Sub 'don't compare End 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 leftvalue rightvalue = Val(txtright.text) 'convert the text in the txtright text box to a number and store in rightvalue

(Continued on next page)

If leftvalue > rightvalue Then

(37)

ElseIf rightvalue > leftvalue Then

MsgBox "The Right Text Box Value Was Greater", , "Comparison Result" 'tell the user that the right value was greater Else 'the two values must be equal

MsgBox "The Two Values Are Equal", , "Comparison Result" 'so tell the user End If

txtleft.text = "" 'clear the left text box txtright.text = "" 'clear the right text box End Sub

The cmdexit_click procedure should contain the code: Sub cmdexit_Click ()

End End Sub

(38)

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.

(39)

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

'All variables must be declared Option Explicit

The cmdexit_click procedure should contain the code: Sub cmdexit_Click ()

End End Sub

The cmdask_click procedure should contain the code:

Sub cmdask_Click () Dim username Dim responsedate asknameagain:

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

If 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 user

If 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

(40)

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 pressed 2: The right mouse button was pressed 4: 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 depressed 4: The Alt key was depressed

x: The sum of the values for multiple keys depressed

Example: 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

(41)

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 Points

Pixels: The number of pixels per inch is a function of monitor resolution Inches

Millimeters Centimeters

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

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

(42)

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. When menu design is complete, the menu control list box should appear as in Figure 7.

(43)

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.

(44)

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 Control

2. The Shape Control 3. The Picture Control 4. 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.

• 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 Description 0 (Default) Rectangle 1 Square 2 Oval 3 Circle 4 Rounded Rectangle 5 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.

(45)

• 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 object

top = the new vertical coordinate for the top edge of the object

width = the new width of the object

height = the new height of the object

(46)

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 Caption

mnurectangle &Rectangle

mnusquare &Square

mnuoval &Oval

mnucircle C&ircle

mnuroundedrectangle Rounded R&ectangle

mnuroundedsquare Rounded S&quare

(47)

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.

(48)

Figure 10: The Tracker Form

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

'all variables must be declared Option Explicit

Dim shapeflag ‘this is the variable that tells us which shape to drop into the form

Dim insertx ‘this is the variable that tells us the mouse pointer’s current x position

Dim inserty ‘this is the variable that tells us the mouse pointer’s current y position

(49)

Sub Form_MouseMove (Button As Integer, Shift As Integer, x As Single, y As Single) txtx.text = x ‘update x coordinate display

txty.text = y ‘update y coordinate display

insertx=x ‘make the x coordinate visible to all procedures

inserty=y ‘make the y coordinate visible to all procedures

End Sub

The mnuexit_click procedure should contain the code: Sub mnuexit_Click ()

End End Sub

The mnucircle_click procedure should contain the code: Sub mnucircle_Click ()

shapeflag = 3 ‘set the shapeflag for circle

End Sub

The mnuoval_click procedure should contain the code: Sub mnuoval_Click ()

shapeflag = 2 ‘set the shapeflag for oval

End Sub

The mnurectangle_click procedure should contain the code: Sub mnurectangle_Click ()

shapeflag = 0 ‘set the shapeflag for rectangle

End Sub

The mnuroundedrectangle_click procedure should contain the code: Sub mnuroundedrectangle_Click ()

shapeflag = 4 ‘set the shapeflag for rounded rectangle

End Sub

The mnuroundedsquare_click procedure should contain the code: Sub mnuroundedsquare_Click ()

shapeflag = 5 ‘set the shapeflag for rounded square

End Sub

The mnusquare_click procedure should contain the code: Sub mnusquare_Click ()

(50)

shapeflag = 1 ‘set the shapeflag for square End Sub

The form_click procedure should contain the code: Sub Form_Click ()

shpinsert.Shape = shapeflag 'set the shape property to the user selected value

shpinsert.Left = insertx 'set the left edge of the shape at the current x coordinate

shpinsert.Top = inserty 'set the top edge of the shape at the current y coordinate

shpinsert.Visible = True 'make the shape visible End Sub

The form_dblclick procedure should contain the code: Sub Form_DblClick ()

shpinsert.Visible = False 'clear the form End Sub

(51)

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:

thisvariable

thisvariable <= 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.

(52)

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:

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:

References

Related documents

You find out how to launch Visual Studio 2005 (the development tool for your VB applications), how to start a new project, and how to build a form visually and make it work with

We will follow the steps shown in Figure 1.12, which are sketch the part and form, start the program, create the form, declare the variables, do the math, make the point

The general form of the switch statement is switch(expression) { case constant1: statement sequence break; case constant2: statement sequence break; case constant3: statement

Standard Modules store procedures that can be used by any form or report that is within your database, whereas Form Modules or Report Modules are assigned to a specific form

The declaration of declared outside of local variables are assigned is created later use an instance methods can declare and declarations often confuses people may be

While a local variable can be used only inside a function in which it is declared, a global variable can be used anywhere in the program... Block Variables: Yet another place

In command button the _____ property is used to change the label value for any content.. In visual basic the _____ file consist of complete coding and

You find out how to launch Visual Studio 2008 (the development tool for your VB applications), how to start a new project, and how to build a form visually and make it work with