This action might not be possible to undo. Are you sure you want to continue?
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
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 List Box Ver. Scroll Bar Drive List Box File List Box Dir. List Box
Label Frame Check Box Combo Box Hor. Scroll Bar Timer
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.
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 Caption Height Width Top Identifies the object and all associated procedures. Displays messages, etc., on the object both during design-time and during run-time. Defines the vertical dimension of the object. Defines the horizontal dimension of the object. 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. : : : : :
Variable Types: Visual Basic supports all of the variable types used with QuickBASIC. II. During this short course. LINE INPUT.caption = “I’m showing you” When object properties are referenced in code. A variable declared as a variant may contain either a string or a numerical value. the statement: DIM thisvariable declares the variable thisvariable as a variant. GLOBAL. In general. Visual Basic allows the programmer to use the variant data type. to change its caption to “I’m showing you”. Using the mouse. 2. INPUT. Left. if we had created a form named frmshowme during design time. 5 . during run time. we will discuss the ways in which Visual Basic receives user input from both the mouse and the keyboard. The option explicit forces the declaration of all variables. the syntax shown in the statement above is used. 3. 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 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. In addition. 2. and STATIC statements. and is placed in the general declarations procedure of a form. REDIM. Height and Width in the Properties Window.Object properties can be set/changed during design time using the properties window. or other keyboard driven statements that you may be familiar with in the QuickBASIC context. Properties can also be changed during run-time from code. Variable Definitions: Visual Basic supports the use of the option explicit statement. For example. Code Generation Many of the keywords used by QuickBASIC are also used by Visual Basic. User input: Visual Basic does not support the use of INKEY$. For example. Some major differences between the two languages exist in the areas of: 1. The variant data type is Visual Basic’s default. and wished. we could execute the code statement: frmshowme. Variables are declared using the DIM. Specifying numerical values for Top. The data types supported by Visual Basic are shown in Table I.
147. 4.337.Data Type Integer Long (Long Integer) Single (Single Precision Floating Point) Double (Double Precision Floating Point) Suffix % & ! Storage Size 2 bytes 4 bytes 4 bytes Range -32. consider the following BASIC code fragment SCANAGAIN: USERINPUT$ = INKEY$ ‘poll for user input IF USERINPUT$=“” THEN GOTO SCANAGAIN ‘if no input is received. the following code would be executed: SUB cmdstart_click 6 .402823E38 to -1.500 bytes. 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.337.94065645841247E-324 for negative values. For example.477.5807 $ 1 byte/character 0 to approximately 65.203.401298E-45 to 3. poll again This program fragment puts the procedure driven BASIC program into a loop.79769313486232E308 to -4.94065645841247E-324 to 1.203.685. program execution continues with the statement following the IF-THEN statement.483. none Number The range of each element is the Required by same as the range of its fundamental Elements data type.401298E-45 for negative values. with a caption of START.483.684. In event driven programming. 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. Using Visual Basic. If the user clicked the START button.647 Currency (Scaled Integer) String Variant User-Defined (using Type) -3.477. we might create a command button called cmdstart.648 to 2.768 to 32767 -2.79769313486232E308 for positive values @ 8 bytes -922. At this point.402823E38 for positive values # 8 bytes -1.147. 1. Program execution exits the loop only if the user hits a key. listed above. Some storage overhead required.5808 to 922. none As Appropriate Any numeric variable up to the range of a Double or any character text.
by default. cause contents to be loaded into combo and list boxes. we must declare startflag in the General Declarations procedure. is the first event to occur upon start-up of the application (for a startup form). 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. If there are multiple forms in a project. initialize form-level variables. 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. 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. 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 for each form occurs when the form is loaded (as a result of a reference to an unloaded form’s properties or controls). etc. • The Form Load Event The Form Load event. In order to accomplish this.
These special key combinations are known as access key combinations. or the size of an object changes.Note: When a property on an unloaded form is referenced in code. For example. the click event may also occur when the ENTER key is pressed while the object has the focus. the letter after the & symbol will be underlined in the caption. For command buttons and menu items. the caption property of the object must contain the & symbol. along with the ALT key. the form is automatically loaded. repainting is done automatically.. or after a window that was covering the object has been moved out of the way. and that letter. or set the VISIBLE property of the new form to true in its FORM_LOAD event procedure. To set an access key combination for an object. if we create a command button and set its caption to &START. makes up the access key combination for the control. so additional code in the Paint procedure becomes unnecessary. or if a special key combination is pressed.e. When this symbol appears. Occurs when a form first appears. Occurs when part or all of a form or picturebox is exposed after it has been moved or enlarged. only one object hold the focus at any given time. the programmer can ensure that graphics on the form are repainted when necessary. Note that if the AutoRedraw property of the object is TRUE. is able to receive user input using either the mouse or keyboard). To make the new form visible. Using the Paint procedure. Occurs when an object receives the focus (i. Events which are related to the Form Load event are: Activate: GotFocus: Occurs when a form becomes the active window (the window that appears in the foreground with a highlighted border or title bar). Objects can receive the focus only if their Enabled and Visible properties are set to TRUE. you may use the SHOW method. In the Windows environment. but is not made visible to the user. Paint: Resize: • The Click Event This event occurs when the user presses and releases a mouse button while the mouse pointer is over an object. that caption will appear on the command button as: START 8 .
two files are created: 1. we will examine a number of these events. During this short course. right. etc. the Click procedure can be invoked from code by simply typing: objectname_click as a line of code. Form files may be saved in ASCII or binary formats. The Project File: This file has the name of the project. since you may occasionally create different projects that use a common form. Note: The Click and DblClick events do not distinguish between the left.FRM. Any modification made to that form will affect all projects using that form. click the SAVE AS TEXT checkbox. just as with any other procedure. during run-time. The Form File: This file has the name of the form. This point is important. 2. and contains the information used by Visual Basic (and specified by the programmer) for building the project. with the extension . and middle mouse buttons. the MouseDown and MouseUp events may be used. Note that. • 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. just as if the user had placed the mouse pointer over the button and clicked. the user presses ALT+S or ALT+s. • Beginning a New Project 9 . including your code. the size of the project window. the object will appear to have experienced two Click events.If. Creating and Saving a Project • Project Files Each time that you begin a new project.VBP. such as the location of Visual Basics custom controls. If it is important to know which mouse buttons have been clicked. depending on the control object being discussed. with the extension . the Click event for this button will occur. The default file format is binary. To save the form and project files in ASCII format. if the form is saved with the same name. If the DblClick event does not occur within the system’s double-click time limit. There are many other types of events. and contains information concerning the form. III.
Start Visual Basic by double clicking its icon. and these controls (. Note: Do not use the default . the toolbox is displayed at the left side of the screen. Note: If no Project Window is displayed.VBP file. Exercise 1 Note: 10 . you can cause this window to appear by using the Window/Project menu options. A “Save File As “ dialog box will appear with the query: Save changes to Form1. In addition. to make a backup copy.FRM and . Choose a directory in which to save the project. which shows the forms. which by default is Project 1.VBP file so that more or fewer controls are loaded automatically upon new project creation. This file causes a set of Visual Basic custom controls to be available to the user. Note: If no Properties Window is displayed. you can cause this window to appear by using the Window/Project menu options. before modifying the AUTOLOAD.frm? Select the YES button. The caption of the Project Window is the name of the current project.MAK files with names that are descriptive of the project being designed. Select the File/New Project menu options. and the menu bar is displayed at the top of the screen.VBX files) are shown in the project window. 3. The programmer may modify the AUTOLOAD. save the .VBP file is loaded. and enter a name for the new form. which shows the properties of the current object. the AUTOLOAD. 2. ii) The Project Window.VBP file to be saved. Enter the name for the . iii) The Properties Window. Instead. A “Save Project As” dialog box will appear. Each time you begin a new project. It is advisable. Save the new project using the File/Save Project As menu options. including: i) A blank form with the caption Form 1.1.VBP file names supplied by Visual Basic.FRM and . modules. and custom controls included in the current project. Visual Basic will display a number of windows on the desktop.
Change the name of the form to: frmmessages 4. i) Select the name property.frm and the make file as messages. 4. Select the File/New Project menu options. Select the File/Save Project As menu options. double click the command button icon. Change the name of the command button to: cmdend ii) Select the caption property. i) Select the name property and change it to: cmddisplaynextmessage 11 . double click the command button icon. On the toolbox. Start Visual Basic. Change the caption of the command button to: &End 6. Make sure that the properties window indicates the new command button. i) In the properties window. 7. Drag the command button to the lower right corner of the form. select the caption property. • Procedure: 1. Drag the command button to the lower left corner of the form. 2. Click the form to make sure that it is selected. Save the form as messages. On the toolbox.Create and execute a simple application which displays one of three messages when a “display message” command button is clicked. Make sure that the properties window indicates the new command button. 5. A new command button is created. select the name property. Allow the user to end program execution when an “End” command button is clicked. A new command button is created. Change the caption of the form to: Three Messages ii) In the properties window. 3.mak.
and its height is at least 492. 8.Fixed Single by double clicking this property in the property window. The visual implementation of this program is complete. The form should appear as shown in Figure 3. On the toolbox. iv)Set the border style property to: 1 . Make sure that the properties window indicates the new label. Drag the new label to the top center of the form. or type these values into the height and width properties in the properties window. 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. A new label is created.ii) Select the caption property and change it to: &Display Next Message iii)Resize the command button so that the entire caption is displayed. double click the label icon (the icon with a capital A). 9. You may use the mouse. Save the project before proceeding. 12 .
The third line declares the variable messagecounter as a variant. Make sure that the Procedure list box displays the Declarations procedure. The second line makes the comment true by issuing the Option Explicit Statement. Since this variable is declared in the General Declarations area of the form. The code window appears. 13 . Double click any blank region of the form. Use the Object list box at the top of the code window to choose the General object.Figure 3: The Three Messages Form Now write the code for this application. Note that the code window may also be made visible by choosing the View/Code menu options. 1. it is visible to all procedures in the form. 2. 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.
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. “Second message”. and “Third message”. Type in the Form_Load procedure code shown below. It causes the caption of the lblmessage label to read “No messages”. 14 . the REDIM statement must be used. Sub Form_Load () lblmessage. Sub cmdend_Click () Beep End End Sub When the Click event occurs on the cmdend command button object. 2.Caption = message(messagecounter) End Sub The first line dimensions a local array called message() as a variant. messages 1. 5. or in an external Basic Module). the PC emits a beep. and three are defined as “First message”. When dimensioning arrays at the procedure level (as opposed to dimensioning them in the General Declarations code of the form. Type in the cmdend_click procedure code shown below. 4. Now type in the code for the cmddisplaymessage command button Click procedure. Use the object and procedure list boxes to go to the cmdend_click procedure. This array will hold the three messages which will be displayed in the lblmessage label.Caption = "No messages" End Sub This section of code is executed at application startup. Next.3. Use the object and procedure list boxes to go to the Form_Load procedure. and then program execution terminates.
If the message counter has grown too large (i. the message is displayed by setting the caption property of the lblmessage label equal to message(messagecounter). you may click the button using the enter key or the mouse. Note also that if a button does not have the focus.The next line increments the messagecounter variable. The next three lines constitute a block-if statement. Finally. which is to be used as a subscript reference for the message() array.e. or by choosing the Run/End menu options. if it is larger then three). 15 . then it is set back to 1 so that the first message may be repeated. You may exit the application using the cmdend command button. Note that you may give command buttons the focus by using either the mouse or the tab key. Now run the program by choosing the Run/Start menu options. When a button has 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).
Click the form to make sure that it is selected. 16 . Save the project. Select the File/New Project menu options. and change the form’s caption to “White Form”. 2. The form should appear as in Figure 4.frm and the make file as colors. 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. 3. 7.mak. Allow the user to exit the program using a command button. i) Change the form’s caption to: The Colors Program ii) Change the form’s name to: frmcolors 6. set the background color of the form to bright white. Start Visual Basic. 5. Create a new command button by double clicking the command button icon in the toolbox. • Procedure: 1. Select the File/Save Project As menu options.Exercise 2 Create and execute an application that changes the color of the form randomly each time the form receives a Form_Click event. 4. If the form receives a Form_DblClick event. Save the form as colors.
The form_click procedure should contain the code: Sub Form_Click () Dim color color = Int(16 * Rnd) frmcolors.BackColor = QBColor(color) 'declare the color variable 'find a random qbcolor number 'set the form's background color 'equal to the random color we just 'generated frmcolors. and QBCOLOR functions.caption="The Colors Program" End Sub This code makes use of Visual Basic’s RND. program execution terminates. The cmdend_click procedure should contain the code: Sub cmdend_Click () End End Sub When the cmdend command button is clicked. 1.Figure 4: The Colors Form Now begin the Code Generation phase of this project. 2. 17 . INT .
so the function will return an integer between 0 and 15.The line: Dim color declares the variable color as a variant. The INT function returns the integer portion of its argument. 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. The RND keyword returns a decimal value between 0 and 1. The argument supplied to the INT function in this case is a real number between 0 and 16. and the colors they represent.caption="The Colors Program" sets the caption of the form to “The Colors Program”. The line: color=Int(16*Rnd) sets the variable color equal to an integer value between 0 and 15. The line: frmcolors. colors may also be set using the RGB function. we have a real number between 0 and 16. Table II lists acceptable arguments for the QBCOLOR function. If we multiply this value by 16. 18 . The QBCOLOR function sets a color based on its argument.
its caption is changed to “White Form”. 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.Finally.BackColor = QBColor(color) sets the background color of the form to the color generated by the QBCOLOR statement.caption = "White Form" 'change the form's caption End Sub When the form experiences a double-click event. 3. the line: frmcolors. At the same time. 19 . bright white. its background color is set to QBCOLOR(15).
an event procedure remains idle until the object the its code is associated with experiences the event referenced by the event procedure. Select the View/New Procedure menu options. it is a set of instructions that allow the application to perform a specific task. In the code window. Event procedures are created for the programmer at the time of creation of the control object with which they are associated. General procedures which are placed in a form may be accessed only from within that form. The use of general procedures helps compartmentalize complex code into easily understandable segments. Rather. Open the code window for the form or module which is to contain the general procedure. type a name for the new general procedure. Functions return values. Methods work similarly to procedures and functions. General procedures may be placed either in form code or in a Basic module. 3. and must be invoked (called) from code. and code may be entered into its template. and are referenced in the same way as variables. but are specific to the object which supports them. Procedures do not return values. For example.IV. General procedures placed in a module may be accessed from within any form or module in the project. To create a general procedure: 1. the name or value of each argument should follow the name of the procedure 20 . Note: Visual Basic also supports the use of functions.K. the form supports a number of graphics methods. General procedures must be created by the programmer during design-time. Select the SUB option button if you wish to create a procedure. The new procedure has been created. In the text box. 4. the new procedure may be found by choosing General in the object list box. 2. These methods are specifically designed functions used to draw on the form. This is why variables declared in the General Declarations area of a form are not visible outside that form. If arguments are to be passed to a procedure. or until the event procedure is invoked from code. Note: Procedures are called from code by typing their name. Choose O. and by choosing the correct procedure name in the Procedure list box. By contrast. 5. Visual Basic Program Flow Control • General and Event Procedures A general procedure is not associated with a particular object or event. Select the FUNCTION option button to create a function. Visual Basic also supports the use of methods.
sub stepit(x. The code for the stepit procedure is given below.y. the argument list should be enclosed in parentheses. and a z value of 6.4.6) End Sub The code shown below is also equivalent: Sub cmdmove_click DIM sendxvalue 21 . The code of the cmdmove_click procedure might look like this: Sub cmdmove_click stepit 2. If the CALL keyword is used.z) x=x+1 y=y+1 z=z+1 End Sub Suppose that we have a command button named cmdmove. must be enclosed in parentheses. Visual Basic supports the use of the CALL keyword. Arguments in this list should be separated by commas. Arguments passed to functions. we want to call the stepit procedure.6 End Sub The following code is equivalent: Sub cmdmove_click CALL stepit(2. on the other hand.4.being called. Example: Suppose that we have created a general procedure named stepit. and that when this button is clicked. a y value of 4. and pass it an x value of 2. but this word is optional.
Make the Project window active. Much of this confusion can be avoided by the use of the Option Explicit statement in the General Declarations procedure.sendyvalue. and the third argument passed as the local variable z. both local and global. 2.sendzvalue End Sub In each of the three cases shown above. (i. 'all variables must be declared Option Explicit • Declaring Global Variables If only a single form is used in a project. The Option Explicit statement forces the declaration of all variables.DIM sendyvalue DIM sendzvalue sendxvalue = 2 sendyvalue = 4 sendzvalue = 6 stepit sendxvalue. and reads in the first argument passed to it as its local variable x.e. must appear in the General Declarations procedure.. since those variables are visible to all procedures associated with the form. • The Option Explicit Statement While developing complex applications. then variables that must be visible to procedures in all forms. Example: The General Declarations procedure shown below uses the Option Explicit statement. the second passed argument as the local variable y. confusion can arise due to mis-spelled variable names and the re-use of the same variable name locally in several procedures. Select the File/New Module menu options. 22 . To create a Basic Module: 1. then variables declared using a DIM statement in the General Declarations procedure of that form may be considered to be global. variables that are to be global to the project). the stepit sub procedure is invoked. if used. The Option Explicit statement. must be declared in a Basic Module using the GLOBAL statement. If more than one form exists in a project.
. 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. Variables may be declared using the DIM or STATIC statements. V..variablename You may also define arrays using the GLOBAL statement. and specify Visual Basic data types. local. Variables declared with the STATIC statement retain their values from one procedure execution to the next. A sample global type declaration is shown below. etc.3. Arrays may be declared locally within a procedure. This statement uses the value of an expression to control the order in which program statements are executed. . GLOBAL myinteger AS INTEGER • Declaring Local Variables Variables declared in form or module procedures other than the General Declarations procedure are. and save the file with the desired name and a .). and should appear in the project window. variablename. At this point. the new Basic Module has been added to your project. This allows the programmer to use the same variable name in multiple procedures without fear of confusion or incorrect variable values. string. Select the File/Save File As menu options. These statements may also be used with the keyword AS to define a variable type (integer.BAS extension.. To declare a local array. Variables declared with the DIM statement are reinitialized to zero each time the procedure is executed. 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. Flow Control Statements • IF-THEN Statements The Visual Basic IF-THEN statement has the same structure as the QuickBasic IF-THEN statement. the REDIM statement must be used. by default. 23 . These variables are visible only within the procedure where they are declared.
then execute the cmdstart_click event procedure. The Block IF-THEN statement: 24 IF NOT x THEN EXIT SUB If x is a non-zero number. then exit the procedure currently being executed. iv) IF x < 4 OR x = y THEN cmdstart_dblclick If either expression is TRUE (i. iii) IF x = 1 AND y >= 3 THEN cmdstart_click If both expressions are TRUE (i..e.The IF-THEN statement tests the equivalence of two expressions.. vi) executed. If x + 2 is equal to y/5. These comparisons can be combined using the logical operators AND. OR. then add 1 to z. 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. v) IF x AND y THEN EXIT SUB If both x and y are non-zero. if x equals 1 and y is greater than or equal to 3). 2. then set z equal to 0. and NOT. then exit the procedure currently being = = = a comparison of two values that yields TRUE or FALSE the action to be taken if the expression(s) is TRUE the action to be taken if the expression(s) is FALSE . if x is less than 4 or if x is equal to y) then execute the cmdstart_dblclick procedure. 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.e. The single line IF-THEN statement: IF expression AND expression OR expression THEN true ELSE false where: expression true false Examples: i) IF x = y THEN GOTO skiptherest If it is true that x is equal to y. The syntax of the IF-THEN statement can take one of two forms: 1.
. OR’s. 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 25 . just as they can with the single line version of the IF then statement.IF expression1 THEN truestatements1 ELSEIF expression2 THEN truestatements2 . ELSE falsestmnts END IF where: expression1 expression2 true1 true2 falsestmnts the = = = = = a comparison of two values that yields TRUE or FALSE a comparison of two values that yields TRUE or FALSE A set of statements to be executed only if expression1 yields TRUE A set of statements to be executed only if expression2 yields TRUE A set of statements to be executed only if none of the expressions in the IF or ELSEIF lines of block IF yields TRUE Expressions can be combined in the IF and ELSEIF lines of the block IF statement using AND’s. . and NOT’s.
In both cases (single line and block syntax).e. 3.ELSE a=3 END IF The block IF statement above is equivalent to the set of single line IF-THEN statements shown below. ELSE’s and ELSEIF’s are optional. This is a particularly important point to note when working with variant data types. the ISNUMERIC function returns TRUE (i. 1). 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. It is permissible to nest block IF-THEN statements. It is not permissible to compare a string variable to a numeric variable. numeric to numeric or string to string). 2.. OR’s. if the variable contains a number). If for some reason an END IF statement is omitted. Each block IF statement must possess an END IF. Comparisons must be made between like variable types (i.e.. NOT’s. The syntax of the ISNUMERIC function is: ISNUMERIC(variant) If the variant can be converted to a numeric data type (i. • The ISNUMERIC Function The ISNUMERIC function returns a value indicating whether or not a variant variable can be converted to a numeric data type. AND’s. 26 . which may contain either numeric or string variables. you will often see errors such as “Block IF without END IF” or “NEXT without FOR”.e. z is incremented by 1 only if x = y and x > 5 4. The ISNUMERIC function is useful when working with variant data types. IF x = y THEN IF x > 5 THEN z=z+1 END IF END IF In the example shown..
the ISNUMERIC function returns a FALSE (i.e. 0). Sub cmdstart_click DIM whatami whatami = 5 IF ISNUMERIC(whatami) THEN txtwhatheis. • The SELECT CASE Statement 27 . Example: Consider the following code fragment.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.text = “He’s a number” ELSE txtwhatheis. if the variable contains a string)..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.text = “He’s a number” ELSE txtwhatheis..e. 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.If the variant cannot be converted to a numeric data type (i.
then the addtransactions procedure is executed. Example: Consider the code fragment below. not a TRUE or FALSE value a constant expression a set of statements to be executed if expression = comparison1 OR expression = comparison2 a set of statements to be executed if expression = comparison3 OR expression = comparison4 a set of statements to be executed if no comparison is true. This value must be a constant.comparison4 statements2 CASE ELSE statements3 END SELECT where: expression comparisoni statements1 statements2 statements3 = = = = = the variable being compared. then the addcustomers procedure is executed. SELECT CASE userinput$ CASE “Y”. Example: Consider the code fragment below. or the switch statement in C. SELECT CASE menunumber CASE 1 addcustomers CASE 2 addtransactions END SELECT If menunumber is equal to 1. ”y” doit 28 .The SELECT CASE statement is analogous to the CASE statement in Pascal. The syntax of the SELECT CASE statement is: SELECT CASE expression CASE comparison1. If menunumber equals 2.comparison2 statements1 CASE comparison3.
and may cause unexpected results. 29 . • FOR-NEXT Loops FOR-NEXT loops are used to repeat a group of instructions some specified number of times. “n” Exit Sub END SELECT If the string userinput$ is equal to “Y” or equal to “y” then the doit procedure is executed. then increment defaults to 1. When the NEXT statement is encountered. It is not permissible to use array elements as loop counters. execution branches back to the FOR statement if counter<=end. If the evaluation fails. execution branches back to the FOR statement if counter>=end. Notes: 1. If userinput$ is equal to “N” or “n” then the current procedure is exited. When increment is negative. and an evaluation of counter is made. increment is added to counter. If no STEP is specified. Note: Comparison expressions can be ranges using the TO keyword. the final value for counter the amount by which the counter is incremented each time that the loop executes a group of statements that is executed each time that the loop executes Note: The STEP keyword is optional. The syntax for the FOR-NEXT loop is: FOR counter = start TO end STEP increment statement block NEXT counter where: counter end increment statement block = = = = a variable used as the loop counter. Changing the value of counter while inside a loop makes the program difficult to debug. The FOR-NEXT loop begins with the FOR statement. When increment is positive.CASE “N”. Program execution continues downward until the NEXT statement is encountered. program execution continues with the statement following NEXT.
text = STR$(y) NEXT y NEXT x This code fragment causes the text box txtshownumber to display. Since y may be numeric (depending on how it was declared). was used. Example: Consider the code fragment below. Note: The text property of a text box must contain a string value. control is transferred to the statement following the NEXT statement. FOR x = 1 to 5 FOR y = 6 to 2 STEP -1 txtshownumber. • The EXIT FOR Statement When the EXIT FOR statement is executed. which converts numbers to strings. the STR$ function. The syntax of the DO-LOOP is: DO WHILE expression statements LOOP or DO UNTIL expression statements LOOP or DO 30 . EXIT FOR exits only the current FOR-NEXT loop. FOR-NEXT loops may be nested. control is transferred to the loop that is one nested level above the current loop. (in this order).2. • 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 numbers 6 5 4 3 2 This process is repeated 5 times. When the EXIT FOR statement is executed within a nested FOR-NEXT loop.
When used within nested DO-LOOP statements. VI. • The EXIT FUNCTION Statement The EXIT FUNCTION statement is used to exit a function. • Message Boxes 31 . • The EXIT DO Statement The EXIT DO statement transfers control to the statement following the LOOP statement. the user can provide input by means of Message Boxes. EXIT DO transfers control to the loop that is one nested level above the current loop. Text Boxes. x=0 DO WHILE x < 10 x=x+1 LOOP The loop will be executed 10 times. and Input Boxes.statements LOOP WHILE expression or DO statements LOOP UNTIL expression where: expression statements = = an expression that evaluates to TRUE or FALSE a block of statements to be executed WHILE or UNTIL expression is TRUE Example: Consider the code fragment below. and is analogous to the EXIT SUB statement. Visual Basic User Input In a Visual Basic application. • The EXIT SUB Statement The EXIT SUB statement immediately exits the procedure in which it appears. with x being incremented by 1 upon each execution.
Retry. but does not return a value.title) Statement Syntax: MsgBox msg.type.type. The MSGBOX function returns a value indicating which button was pushed by the user to clear the message box.The programmer can cause a message box to be displayed using either the MSGBOX statement or the MSGBOX function. Message boxes are generated during run-time by statements in code. and Ignore buttons Display Yes. the icon style to use.title where: msg = the message to be displayed. The MSGBOX statement simply displays a message. No. The application displaying the message box is “frozen” until the user clears the message box by pushing a button. An application modal message box allows the user to operate in applications other than the application displaying the message box. Value 0 1 2 3 4 5 16 32 64 0 4096 Meaning Display OK button only Display OK and Cancel buttons Display Abort. and Cancel buttons Display Yes and No buttons Display Retry and Cancel buttons Use the STOP icon Use the Questionmark icon Use the exclamation point icon Application modal 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. type = a numeric expression that is the sum of the values specifying the number and type of buttons to display. 32 . or a string enclosed in quotes. Function Syntax: variable = MsgBox (msg. This can be a string or variant variable. 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.
title. a text box. 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. or an expression quotes. If the OK button was clicked. A string expression or string/variant variable to be displayed in the text box as the default response. in twips. the Input Box returns the contents of the text box. Table IV lists the values returned by the msgbox function. of the left edge of the dialog box. A string expression or string/variant variable to be displayed in the title bar of the dialog box. ypos) where: variable prompt This enclosed in title default xpos = = = = = The variable into which the user’s response is to be placed.e. may be a string or variant variable. default. Input Boxes are generated during run-time by statements in code. A string expression displayed in the dialog box as a message. The location. the Input Box returns null (i. 33 . The user may type inside the text box and then close the dialog box by clicking either button. The syntax for displaying an Input Box is: variable = InputBox (prompt. “”.. If the Cancel button was clicked. xpos. a zero length string). an OK button and a Cancel button.A system modal message box forces the user to respond to the message box before any action can be taken in any application.
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. xpos. Text may be inserted into a text box either during runtime or during design-time by altering the TEXT property of the text box. of the top edge of the dialog box. which are generated during run-time by statements in code. 34 . and changed. in twips. Note: Title. the TEXT property of the text box may be treated as a variable. default. • Text Boxes Text boxes are control objects created during design-time.ypos = The location. It may be read. manipulated. In effect. and ypos are optional. as opposed to Input Boxes and Message Boxes. Text boxes are rectangular areas where text is displayed.
Exercise 3 Write a program that allows the user to enter numbers into two text boxes. 5. and place it in the lower left corner of the form. force the user to re-enter that number. Once the user has completed entry. Name the command button cmdcompare. Name the command button cmdexit. and clear the text from each text box. Procedure: 1. and place it in the upper left corner of the form (the text box icon in the tool box has the letters ab displayed). 6. 4. and place it in the lower right corner of the form. and change its text property to “” (a null string). 2. and change its caption to &Compare. Create a text box. display a message box that states which text box contained the greater number. Change the text box name to txtleft and its text property to “” (a null string). Change the form’s caption to: The Comparison Program and its name to: frmcompare 3. The visual implementation of the program is complete. Create a project. The user should be able to exit the program using a command button. If the user enters a non-numeric value into either text box.frm. Create a text box. Create a command button. and place it in the upper right corner of the form.mak and the form file as compare. Save the project before continuing. The form should appear as shown in Figure 5. Create a command button. 35 . and change its caption to &Exit. Name the text box txtright. Save the make file as compare.
"Warning .text) Then 'if the right text box doesn't contain a number MsgBox txtright. 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.". Please Re-Enter. Please Re-Enter. . both values must be numeric.text) Then 'if the left text box doesn't contain a number MsgBox txtleft.text) 'convert the text in the txtleft text box to a number and store in leftvalue 'convert the text in the txtright text box to a number and store in rightvalue (Continued on next page) If leftvalue > rightvalue Then MsgBox "The Left Text Box Value Was Greater". "Warning .Right Text Box" 'ask the user to re-enter Exit Sub 'don't compare End If 'if we have gotten this far. . "Comparison Result" 'tell the user that the left value was greater 36 .Left Text Box" 'ask the user to re-enter Exit Sub 'don't compare values End If If Not IsNumeric(txtright. so we can compare them leftvalue = Val(txtleft.Figure 5: The Compare Form Now write the code for the Compare program.text + " Is Not Numeric.".text) rightvalue = Val(txtright.text + " Is Not Numeric. .
ElseIf rightvalue > leftvalue Then MsgBox "The Right Text Box Value Was Greater", , "Comparison Result" Else MsgBox "The Two Values Are Equal", , "Comparison Result" End If txtleft.text = "" txtright.text = "" End Sub
'tell the user that the right value was greater 'the two values must be equal 'so tell the user 'clear the left text box 'clear the right text box
The cmdexit_click procedure should contain the code: Sub cmdexit_Click () End End Sub Note the use of the VAL function, which converts string values into numeric values.
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
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") If IsNumeric(username) Then GoTo asknameagain askdateagain: responsedate = InputBox("Please Enter a Date", "Query: Date") If Not IsDate(responsedate) Then GoTo askdateagain frmnameanddate.Caption = username + " " + responsedate End Sub 'get the user's name, and store it in ‘username 'if the user responded with a number, ask ‘for the name again 'get a date from the user 'if the response was not a date, then ask for ‘the date again 'change the caption of the form to display ‘the name and date
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 Button Description 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 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. 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
The syntax of the MouseDown event procedure declaration is: Sub MouseMove (Button as Integer. 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. exclusive of the borders and title bar. • The MouseMove Event This event occurs when the user moves the mouse pointer across an object. Note that the form.0). The default values assigned by Visual Basic for these properties are: (ScaleLeft. The MouseMove event is generated continuously as the mouse pointer moves across objects. X as Single. 41 . These properties are not available at design-time. X as Single. The default unit is the twip. is taken to mean the form’s usable area. ScaleTop) = (0. Shift as Integer. Objects receive the MouseMove event when the mouse pointer is within their borders.0) so the upper left corner of the form is at (0. listed in Table V. Y as Single) The MouseUp arguments are the same as those for the MouseDown event procedure. • The Form Coordinate System The coordinates for a form may be specified using a number of different types of units.This event occurs when the user releases a mouse button. Shift as Integer. • The CurrentX and CurrentY Properties These properties determine the horizontal and vertical coordinates for the next printing or graphics method. in this context. The units used are defined by the ScaleMode property of the form. Y as Single) The arguments for this procedure are the same as those listed in Table V. The syntax of the MouseDown event procedure declaration is: Sub MouseUp (Button as Integer.
&Print. File and Edit.VIII. but rather serve as a “door” which allows the user access to a group of menu items. type in a caption. 42 . and &Exit. The menu design window will be displayed. To create a menu item. and Paste menu items. Copy. When creating a menu item. 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. Example: Suppose that we wish to create a menu bar with two menu titles. Menu items are control objects. the menu control properties dialog box is visible. the menu control list box should appear as in Figure 7. follow the procedure given below. When menu design is complete. If we create a menu title &File. right and left arrow buttons are displayed. At its top. 4. each of which executes some code when clicked. and Exit menu items. &Close. At the top of the menu item list box. Menu items appear right aligned in the menu item list box. Under the File menu title. At its bottom. and can experience Click events. Click the form to ensure that it is selected. we might create a menu title with the caption &File. and their names are preceded in the list box by periods (. Menu Titles appear left aligned in the menu item list box. we might create under it a number of menu items with captions such as &Open. When creating a menu title. 1.). Menu Design Menu bars can be included in the Visual Basic application. we wish to place the Open. For example. and a menu item name. 2. 3. Under the Edit menu title. we wish to place the Cut. we might assign it the name mnufile.. use the right arrow button to place the object in the correct position in the menu hierarchy. These buttons are used to create a menu hierarchy. use the right arrow button to place the object in the correct position in the menu hierarchy. the menu control list box can be seen. Close.. To add a menu item. Choose the Window/Menu Design menu options. Menu items fall into two classes: Menu Titles: These items usually do not have attached code. Menu Items: These items have attached code in their Click procedures.
The File menu is expanded so that its menu items are visible.Figure 7: A Menu Design Window Figure 8 shows the form with the menu just designed. Figure 8: The File Menu 43 .
4. or diagonal line. However. or in addition to. 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. X2. but many of the properties possessed by the picture box are not possessed by the image control. this control may appear as a rectangle. The image control uses fewer resources and repaints more quickly than a picture box. or rounded square.Y1.Code can be written into the Click procedure for a menu item just as for any other control. the line method. This control can be used at design-time to draw lines on forms. or during run-time instead of. rounded rectangle. Graphic Controls Visual Basic provides the programmer with several built in graphic controls. square. IX. The start and stop points for the line control are specified by setting its X1. 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. When set to TRUE. this property causes any file loaded into the image control to automatically stretch to fill the control. the image control does support the STRETCH property. 2. 44 . • The Shape Control The shape is a graphic control displayed on the form. circle. Table VI lists the settings and meanings for the shape control’s SHAPE property. The Line Control The Shape Control The Picture Control The Image Control • The Line Control The line is a graphic control displayed as a horizontal. Lines drawn on a form will remain on the form even if the AutoRedraw property of that form is FALSE. oval. and Y2 properties. including: 1. 3. vertical. Line controls may also be displayed in picture boxes and frames.
MOVE left. icons. The syntax for the MOVE method is: objectname. • The MOVE Method This method moves a form or control. set the control’s AutoSize property to TRUE. Note: To cause a picture box to automatically resize to display an entire graphic. top. or metafiles. height where: left top width height = = = = the new horizontal coordinate for the left edge of the object the new vertical coordinate for the top edge of the object the new width of the object the new height of the object Note: Only the left argument is required.• Picture Box Controls These controls can be used to display bitmaps. All other arguments are optional. width. 45 .
a shape should be inserted in the form at the current mouse location. with a caption of &Exit. tracker. Cause their captions to be zero length stings. create the When you are finished. Procedure: 1. Save the form file as tracker. and displays the current x and y coordinates of the mouse in two text boxes (one for the x coordinate. Create a new project. Under it. Create a menu title named mnushape with a caption of &Shape. in the upper left corner of the form. one above the other. and save the make file as 2. following menu items: Name mnurectangle mnusquare mnuoval mnucircle mnuroundedrectangle mnuroundedsquare Caption &Rectangle &Square &Oval C&ircle Rounded R&ectangle Rounded S&quare Under it. If the user clicks the form.mak. and one for the y).frm. create a menu item named mnuexit. Name the top one txtx. Create a menu title named mnufile with a caption of &File. Place them. the menu design window should appear as shown in Figure 9. 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. 4. 3. 46 . and the bottom one txty.Exercise 5 Write a program that continuously tracks mouse position over the form. Create two text boxes.
The visual implementation of the program is complete. Create a shape control and name it shpinsert. Place this label above the txty text box. The completed form should appear as in Figure 10. Name one label lblx.Figure 9: Tracker’s Menu Construction 5. Set the shapes visible property to FALSE. Create two labels. and size them as shown if Figure 10. Name the other label lbly. Place this label above the txtx text box. and give it a caption of Y coordinate. and give it a caption of X coordinate. Save the project. 6. 47 .
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 Dim insertx Dim inserty ‘this is the variable that tells us which shape to drop into the form ‘this is the variable that tells us the mouse pointer’s current x position ‘this is the variable that tells us the mouse pointer’s current y position The form_mousemove procedure should contain the code: 48 .
Sub Form_MouseMove (Button As Integer. Shift As Integer.text = y insertx=x inserty=y End Sub ‘update x coordinate display ‘update y coordinate display ‘make the x coordinate visible to all procedures ‘make the y coordinate visible to all procedures 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 () 49 . x As Single. y As Single) txtx.text = x txty.
Run the program.Shape = shapeflag shpinsert.Top = inserty shpinsert.shapeflag = 1 End Sub ‘set the shapeflag for square The form_click procedure should contain the code: Sub Form_Click () shpinsert.Visible = True End Sub The form_dblclick procedure should contain the code: Sub Form_DblClick () shpinsert.Visible = False End Sub 'clear the form 'set the shape property to the user selected value 'set the left edge of the shape at the current x coordinate 'set the top edge of the shape at the current y coordinate 'make the shape visible The code generation phase of this project is complete. 50 .Left = insertx shpinsert.
Debugging Visual Basic provides a number of debugging tools. Break When Expression Has Changed: Temporarily halt program execution when the value of a variable has changed. Once program execution has been broken. When this command is issued. You may not use the Debug window unless program execution has been temporarily halted by breaking the program. it may be resumed using the run/continue or run/restart menu options. or when the status of an expression has toggled from true to false or from false to true. • The Add Watch Command This command is accessed using the debug/add watch menu options.X. You may break program execution by hitting the CTRL+BREAK keys. • The Edit Watch Command 51 . This expression may be any valid Visual Basic expression such as: thisvariable thisvariable <= thatvariable (thisvariable+thatvariable)=theothervariable etc. a dialog box is displayed into which the programmer may enter a watch expression. Watch expressions are also displayed in the Debug window. Temporarily halt program execution when the expression becomes true. The Add Watch command gives the programmer the options of: Watch Expression: Break When Expression is True: Simply display the value or status of the expression. The status of the watch expression is continuously displayed during run-time in the Debug window. you may print the values of variables from the Debug window). • 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. Some of these tools are described in the following sections. or by choosing the run/break menu options.
Using this command. We might trap this error in the following way: 52 . place the cursor in the line. • The Single Step Command This command is accessed using the debug/single step menu options. the programmer may step through the program one line at a time. watch expressions may be edited. and terminates program execution. • The Toggle Breakpoint Command This command is accessed using the debug/toggle breakpoint menu options. then choose the debug/toggle breakpoint menu options.This command is accessed using the debug/edit watch menu options. To remove all breakpoints from a program. place the cursor anywhere on that line. Using this command. and deleted. To clear the breakpoint from the line of code. program execution is broken if that line of code is reached. but we are concerned about a division by zero error. • The Procedure Step Command This command is accessed using the debug/procedure step menu options. • The ON ERROR GOTO Statement The ON ERROR statement allows the programmer to trap and handle errors that may occur during run-time. When program execution has been broken. To toggle a breakpoint on a line of code. any error that occurs during run-time is fatal. 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. or by pressing F8. If the ON ERROR statement is not used. The line of code will be highlighted to inform the programmer that the line of code has been toggled. the programmer (once program execution has been broken) can step through program execution one procedure at a time. and then choose the debug/toggle breakpoint menu options. This command treats Sub and Function procedures as a single executable statement. We want to set z = x / y. When a breakpoint is toggled on a particular line of code. added. choose the debug/clear all breakpoints menu options. Note: Breakpoints are not saved with the program. The highlighting on the line of code will disappear.
Graphics Methods Using graphics methods. Please make sure that y <> 0”. 3. trap it errorocurred: MSGBOX “An error has ocurred.”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. 4. The two objects most commonly drawn on using graphics methods are the form and the printer. The Points Method The Line Method The Circle Method The CLS Method • The POINT Method The point method is used to draw points on the form (or some other object). y) 53 . “draw” on an object. including: 1. There are a number of graphics methods available to the programmer. the programmer can. The syntax for the point method is: objectname. The RESUME statement causes program execution to continue starting at the line where the error ocurred. 2. The RESUME NEXT statement causes program execution to continue starting at the statement following the program line where the error ocurred.POINT (x.ON ERROR GOTO errorocurred z=x/y EXIT SUB ‘if we get an error. from code.. XI.
y1) (x2. end. CurrentX and CurrentY are set to the endpoint of the line. F where: (x1. y2). y2) causes the box to be filled (solid). • The CIRCLE Method The circle method draws a circle on the form (or some other object). y1) and lower right corner at (x2. y2) color B F = = = = = the starting point for the line the ending point for the line the color for the line (using RGB or QBCOLOR) draws a box with upper left corner at (x1.(x2. radius. The default value for objectname is the current form. When a line is drawn. 3. CurrentX and CurrentY are set to zero. B. aspect where: (x. but their places must be held by commas. y1) and (x2. The default value for objectname is the current form. y) = radius = color = the coordinates of the center of the circle the radius of the circle the color of the circle (using RGB or QBCOLOR) 54 .where: x = the horizontal coordinate of the point to be drawn y = the vertical coordinate of the point to be drawn Note: Objectname is optional. The syntax for the circle method is: objectname. The F argument can only be used in conjunction with the B argument Notes: 1. y2) are optional as well.circle (x. Objectname is optional. color. start. Optional arguments may be omitted from the line statement. y1) . 2. y). All other arguments except (x1.CLS When the cls method is executed. If the point referred to by x and and y is outside the object. • The LINE Method The line method draws a line on the form (or some other object). The syntax for the cls method is: objectname. • The CLS Method The cls method clears text or graphics generated during run-time from a form (or some other object). the point method returns -1. The syntax for the line method is: objectname. color.LINE (x1.
VBX file does not appear in the project window it may be added by following the procedure listed below: 1. Optional arguments may be omitted from the circle statement. 4. The ROW and COL properties of the Grid Control specify the current cell. If the GRID. 4. the circle method will draw a radius to start.start = end = aspect = the starting angle for an arc (in radians) the ending angle for an arc (in radians) the aspect ratio (height/width) for the circle. 3. Choose the File/Add File menu options. Select the file to be added (in this case. The current cell can be specified by setting these properties in code. In order to use the Grid Control. 3. 2. Notes: 1.VBX). Press the OK button. CurrentX and CurrentY are set to the center point of the circle specified.y) and radius arguments are required. Aspect ratios other than one cause ellipses to be drawn. When drawing an arc or ellipse segment. An aspect ratio of one causes a true circle to be drawn.VBX file must appear in the project window during design-time. or the user can select a cell using the mouse or 55 . Note that the intersection of a row and column is referred to as a cell. When the circle method is executed. the GRID. 2. GRID. if start is negative. XII. Select the project window. Only the (x. and will treat the angle to positive. 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. but their places must be held by commas.
. The syntax for the RemoveItem Method is: objectname. 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. These are. the number of the row to be removed (first row has index = 0). set index = 0. The Grid Control’s TEXT property refers to the contents of the current cell. the KeyUp event. Keyboard Events Three events are associated with keyboard activity during run-time. The syntax of the AddItem method is: objectname. • The AddItem Method The AddItem method can be used to add a new row to a Grid Control during run-time.RemoveItem index where: objectname index = = the name of the grid control from which the row is to be removed. Forms can have the 56 . Note that to place a new row in the first row position of a grid. A grid can possess no more than 2000 rows and 400 columns.e. an integer representing the position within the control where the new row is to be placed. Objects can experience keyboard events only if they have the focus (i. etc. index where: objectname item = = the name of the grid control to which the new row is to be added. their border or title bar is highlighted. and the KeyPress event. the KeyDown event.).AddItem item. The Grid Control’s ROWS and COLS properties refer to the size of the grid in rows and columns. XIII.arrow keys on the keyboard. index = • The RemoveItem Method The RemoveItem method is used to remove a row from a grid control.
The possible values for the Shift argument in both the KeyDown and KeyUp events are listed in Table VII. CTRL. = = = the name of the object being referenced a code corresponding to the key that was pressed a code corresponding to the state of the ALT. The syntax for the KeyDown event is: Sub objectname_KeyDown (Keycode as Integer. for the object which has the focus. and CTRL are all not pressed 1 if the SHIFT key only is pressed 2 if the CTRL key only is pressed 4 if the ALT key is pressed 57 . The syntax for the KeyUp event is: Sub objectname_KeyUp (Keycode as Integer. and SHIFT keys Shift Value 0 1 2 3 4 5 6 7 ALT Status CTRL Status SHIFT Status Not Pressed Not Pressed Not Pressed Not Pressed Not Pressed Pressed Not Pressed Pressed Not Pressed Not Pressed Pressed Pressed Pressed Not Pressed Not Pressed Pressed Not Pressed Pressed Pressed Pressed Not Pressed Pressed Pressed Pressed Table VII: Values for the KeyDown. However. Shift as Integer) where: objectname Keycode Shift • The KeyUp Event This event occurs when a key is released. KeyUp Shift Argument Note that the value of the Shift argument is: 0 if SHIFT.focus only if it has no visible or highlighted controls. • The KeyDown Event This event occurs when a key is pressed. if the form’s KeyPreview property is set to TRUE. and Shift have the same meanings as those for the KeyDown event. Shift as Integer) Objectname. Keycode. the form will receive keyboard events before any other object. ALT.
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.TXT file. The syntax for the KeyPress event is: Sub objectname_KeyPress (KeyAscii As Integer) where: objectname KeyAscii = = the name of the object receiving the key stroke the ASCII key code for the key that was pressed Note: The ASCII code for the key combination CTRL+@ is zero. it is good practice to avoid using CTRL+@ in a Visual Basic application. Because Visual Basic recognizes a KeyAscii value of zero as a null (zero length) string. the value of the Shift argument is 1 + 4 = 5. we could create a timer named tmrhello. For example. we could type: txthello.text = “Hello” 58 . In the timer event procedure for tmrhello. XIV.The value of the Shift argument is the sum of the values of the keys which are currently pressed. and set its interval property to 500. The value of the Keycode argument for the KeyDown and KeyUp events corresponds to the values listed in the Visual Basic CONSTANT. • The KeyPress Event The KeyPress event occurs when the user presses a key with an ASCII code. The Timer Control The timer control can be used to execute code at regular intervals by causing a timer event. if the SHIFT and ALT keys are pressed. Example: If we wished to display “Hello” in a text box named txthello every 1/2 second.
Create a timer (by double clicking the stopwatch icon in the toolbox) named tmrdraw. Using a second menu selection. and its MAX property to 15. 59 . 9. Procedure: 1. Size the scroll bar as shown in Figure 11. and size and place it as shown in Figure 11. with a caption Horizontal Lines. Set its caption to a null string. the width of which is controlled by a scroll bar. Set its caption to Horizontal Line Width. The completed form should appear as shown in Figure 11. and save the make file as lines. 5. 10.frm. Create a label named lblwidthdisplay. 8. 7.Exercise 6 Write a program that inserts variable width lines at random orientations every 0. 6. Set the scroll bars MIN property to 1. Create a horizontal scroll bar named hsblinewidth. Under this menu title. Size and place it as shown in Figure 11. Save the form file as lines. 3. Place the command button in the lower right corner of the form. with a caption of Screen. Place the scroll bar between the Start and Stop command buttons. Save the project. Under this menu title. Create a menu title named mnufile. Create a new Visual Basic project. 2. create a menu item named mnuclear with a caption Clear. The user should be able to clear the screen using a menu selection. Place the command button in the lower left corner of the form. and set its caption to The Lines Program. Create a label named lbllinewidth. The visual implementation of this project is complete. Name the form frmlines. the user should be able to draw horizontal lines. with a caption &Start. and continues line insertion until a “Stop” command button is clicked. 4. create a menu item named mnuend. Set the timer’s interval property to 500 milliseconds.5 seconds when a “Start” command button is clicked. Create a menu title named mnuscreen.mak. Also create a menu item named mnuhorizontal. with a caption File. with a caption of End. Create a command button named cmdstart. Create a command button named cmdstop with a caption S&top.
Figure 11: The Lines Form Now begin the code generation phase of the project.startflag End Sub 'toggle the startflag between zero and one The cmdstop_click procedure should contain the code: Sub cmdstop_Click () startflag = 0 'turn the startflag off End Sub The form_load procedure should contain the code: 60 . The General Declarations procedure should contain the code: 'all variables must be declared Option 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 .
Sub Form_Load () lblwidthdisplay.DrawWidth = hsblinewidth.ScaleWidth * Rnd 'pick a random y coordinate between zero 'and the height of the form 'pick a random x ending coordinate between 61 .Cls 'clear the form End Sub The mnuend_click procedure should contain the code: Sub mnuend_Click () End End Sub The mnuhorizontal_click procedure should contain the code: Sub mnuhorizontal_Click () Dim xstart 'declare the line's starting x coordinate Dim y 'declare both lines' y coordinate Dim xend 'declare the line's ending x coordinate frmlines.Value End Sub The mnuclear_click procedure should contain the code: Sub mnuclear_Click () frmlines.Caption = hsblinewidth.ScaleHeight * Rnd xend = frmlines.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 'pick a random x starting coordinate between 'zero and the width of the form 'update the lblwidthdisplay label to reflect 'the current value of the horizontal scroll bar xstart = frmlines.ScaleWidth * Rnd (continued on next page) y = frmlines.Caption = "Default" End Sub 'initialize the caption of the lblwidthdisplay label so 'that it is not blank at startup The hsblinewidth_change procedure should contain the code: Sub hsblinewidth_Change () lblwidthdisplay.
62 .'zero and the width of the form frmlines.ScaleHeight * Rnd frmlines.ScaleWidth * Rnd ystart = frmlines. ystart)-(xend. y)-(xend.ScaleWidth * Rnd yend = frmlines. then don't draw 'set the drawwidth property of the form to 'a number between 1 and 15 so that we can 'draw various width lines 'set the starting x coordinate to a value 'between 0 and the width of the form 'set the starting y coordinate to a value 'between 0 and the height of the form 'set the ending x coordinate to a value 'between 0 and the width of the form 'set the ending y coordinate to a value 'between 0 and the height of the form 'draw the line 'draw the line If startflag <> 1 Then Exit Sub frmlines.ScaleHeight * Rnd xend = frmlines.Line (xstart. yend) End Sub Note: During run-time. Note the difference in the way the application behaves during run-time. minimize the form.DrawWidth = 1 + Int(15 * Rnd) xstart = frmlines. Now change the form’s AutoRedraw property to TRUE. then restore it.Line (xstart. y) End Sub The tmrdraw_timer procedure should contain the code: Sub tmrdraw_Timer () Dim xstart Dim ystart Dim xend Dim yend 'declare the starting x coordinate 'for the randomly oriented lines 'declare the starting y coordinate for 'the randomly oriented lines 'declare the ending x coordinate for 'the randomly oriented lines 'declare the ending y coordinate for 'the randomly oriented lines 'if the startflag is not on. and try this again.
Save the project. create a menu item named mnuend. 3. Create a menu title named mnufile with a caption of File. part prices. Create a new project. and the make file as parts. and its ROWS property to 10.Exercise 7 Write a program that allows the user to fill a grid with part numbers. 63 . Create a grid named grdinventory. The completed form should appear as shown in Figure 12. Under this title. We do not need any fixed columns.mak. Set the grids COLS property to 3. Procedure: 1. 2.frm. Set the FIXEDCOLS property to 0. and in-stock part quantities. Figure 12: The Parts Form Now begin the code generation phase of the project. Note that the FIXEDROWS property is set to 1. with a caption of End. The visual implementation of this project is complete. This gives us one title (fixed) row at the top of the grid. Place the grid top-center on the form. Save the form file as parts.
Text = "Quantity in Stock" For colcounter = 0 To 2 grdinventory.Row = 0 grdinventory. "Cell Entry") 'place the user's response in the current cell grdinventory.Text = response End Sub 'set the current row to zero 'set the current column to zero 'place text in current cell 'set the current column to 1 'place text in the current cell 'set the current column to 2 'place text in the current cell 'step through the columns 'widen the column The grdinventory_keydown procedure should contain the code: Sub grdinventory_KeyDown (keycode As Integer.Col = 1 grdinventory.Col = 2 grdinventory.Text = "Part Number" grdinventory.Text = "Price" grdinventory.ColWidth(colcounter) = 1300 Next 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 cell response = InputBox("Enter Text to Place in Cell". Shift As Integer) 64 .Col = 0 grdinventory.The General Declarations procedure should contain the code: ‘all variables must be declared Option Explicit The form_load procedure should contain the code: Sub Form_Load () Dim colcounter grdinventory.
Run the application.If keycode = &HD Then grdinventory_click End If End Sub 'the enter key was pressed 'act as if a cell had been clicked The mnuend_click procedure should contain the code: Sub mnuend_Click () End End Sub The code generation phase of this project is now complete. 65 .
The File-System Controls These controls include the Directory List Box. Binary Access 3. • The Drive List Box With this box. XVI. or append the device number assigned to the file (an integer between 1 and 255. • The Directory List Box With this box. inclusive) 66 . Sequential Access 2. the user can select disk drives during run-time. and can be opened in one of three ways: 1. For append. these three controls are used in combination. the File List Box. 2. For input. • The File List Box With this box. 3. and the Drive List Box. For output. Random Access We will discuss Binary and Sequential Access. ASCII and Binary File I/O There are three ways to access files using Visual Basic: 1. The syntax for opening a sequential file is: OPEN filename FOR mode AS # filenumber where: filename mode filenumber = = = the path and name of the file to open input. A sample program making use of the File-System controls is given in Appendix A. In a typical application.XV. • Sequential Access Files A sequential file contains ASCII data. the user can select directories and paths during run-time. output. the user can select files during run-time.
“Hisname” PRINT #1. “Hername” CLOSE #1 The file created would have the appearance: Yourname Myname Hisname Hername If we later wished to read this file into an array. “Myname” PRINT #1. Once a file is opened. it must always be closed. 4. “Yourname” PRINT #1. Opening a file in OUTPUT mode destroys the current contents of the file. The APPEND mode sets the file pointer to the end of the file so that new records may be “tacked on”.dat” FOR INPUT AS #1 67 .dat” FOR OUTPUT as #1 PRINT #1. 2.Notes: 1. To close a file. use the statement: CLOSE #filenumber Example: Suppose that we want to create a file containing the words Yourname Myname Hisname Hername We could make use of the following code fragment. OPEN “c:\temp\names. The FREEFILE function returns the value of the first un-used file number. we could use the following code fragment. 3. DIM namesarray(4) DIM namecounter OPEN “c:\temp\names.
FOR namecounter =1 to 4 IF EOF(1) THEN EXIT FOR INPUT #1. namesarray(namecounter) NEXT namecounter CLOSE #1 • Binary Access Files A binary file contains binary data. bytelocation. bytelocation. use the statement: GET #filenumber.contents where: filenumber bytelocation contents = = = the device number assigned to the file the byte location in the file at which writing is to begin the information or variable to be written into the file To read from a binary file. use the statement: PUT #filenumber.variablename where: filenumber = bytelocation = variablename = the device number assigned to the file the byte location within the file at which reading is to begin the name of the variable in which the read information is to be stored 68 . and is opened with the statement: OPEN filename FOR BINARY AS #filenumber To write data into a binary file.
6. and position it above the txtcharacter text box. Procedure: 1. 4.mak. 7. Save the project. Set its text property to null. and position it in the upper right corner of the form. Set the Caption property of the form to “The Keys Program”. Position the text box in the upper left corner of the form. Create a label named lblcode. Create a text box named txtcharacter. 2. 3. Set the KeyPreview property of the form to TRUE. 5. The completed form should appear as in Figure 13.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. Set the name property of the form to frmkeys. Set its text property to null. Create a new project. Create a text box named txtcode. Create a label named lblcharacter. The visual implementation of the project is complete. Save the form file as keys. Set its caption to “Character”. and the make file as keys. Set its caption to &End. and position it in the lower right corner of the form.frm. 69 . Set its caption to “ASCII Code” and position it above the txtcode text box. Create a command button named cmdend.
The General Declarations procedure should contain the code: ‘all variables must be declared Option Explicit The cmdend_click procedure should contain the code: Sub cmdend_Click () End End Sub The form_KeyPress procedure should contain the code: 70 .Figure 13: The Keys Form Now begin the code generation phase of the project.
Sub Form_KeyPress (keyascii As Integer) txtcharacter.Text = keyascii End 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 box txtcharacter.Text = Chr$(keyascii) 'convert the keyascii code into a character 'and display that character in the txtcharacter 'text box 'display the ASCII code in the txtcode text box txtcode. 71 .Text. Run the program. 1) End Sub The code generation phase is complete.Text = Right$(txtcharacter.
Name the form frmphone. and set its caption property to “The Phone Number Program”. create a menu item named mnuaddrow and captioned Add Row.Exercise 9 Write a program that acts as a mini-database for names and phone numbers. 3. The visual implementation of the project is complete. create a menu item named mnuopen with the caption Open. with the caption Save. Create a menu title named mnufile with a caption of File. Procedure: 1. Also create a menu item named mnusave. Name the grid grdphone.mak. Create a menu title named mnugrid and caption Grid. The completed form should appear as in Figure 14. Finally. Create a new project. Save the project. Also create a menu item named mnudeleterow and captioned Delete Row. create a menu item named mnuend with the caption End. Create a grid control with two columns and twenty rows. Under this menu title. Create a 72 . Cause the grid to have one fixed row and no fixed columns. 2. 5. Under this menu title. distribution disk for this program.frm and the make file as phones. Save the form file as phones. 4.
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 declared Option Explicit Dim currentfile 'make the currentfile variable 'visible to all procedures in the 'form The form_load procedure should contain the code: 73 .
Col = 1 grdphone.ColWidth(0) = 3000 grdphone.Text = "Phone" grdphone.RemoveItem grdphone.Sub Form_Load () grdphone.ColWidth(1) = 1500 currentfile = "c:\temp\phone.Row = 0 grdphone. grdphone.Text = "Name" grdphone.dat" End Sub 'set the current row to zero 'set the current column to zero 'fill the current cell 'set the width of column zero wide.AddItem "".SelStartRow End Sub The mnuend_click procedure should contain the code: Sub mnuend_Click () End End Sub The mnuopen_click procedure should contain the code: Sub mnuopen_Click () Dim filetoget 74 .Col = 0 grdphone.SelStartRow End Sub The mnudeleterow_click procedure should contain the code: Sub mnudeleterow_Click () 'delete a row from the grid at the current location grdphone. 'so that it can hold long names 'set the current column to 1 'fill the current cell 'make column 1 wide enough to hold 'phone numbers 'set the currentfile variable to some 'default file name The mnuaddrow_click procedure should contain the code: Sub mnuaddrow_Click () 'add a row to the form at the current location grdphone.
Row = gridrow 'set the current row to gridrow grdphone.Col = 0 'set the current column to zero grdphone. nameofperson 'input a name Input #1. go to the error handling routine Open filetoget For Input As #1 'open the file Do While Not EOF(1) 'if we reach the end of the file.1 For colcounter = 0 To 1 grdphone. gridrow 'add a row to the grid End If grdphone.Rows . .Rows . "Filename".Col = colcounter grdphone. phone 'input a phone number gridrow = gridrow + 1 'increment the gridrow counter If gridrow > (grdphone.Text = "" Next colcounter Next rowcounter Exit Sub cantopenit: MsgBox "Cannot Open File".Text = phone 'place the phone number into the grid Loop 'loop until we reach the end of the file Close #1 'close the file For rowcounter = gridrow + 1 To grdphone.Col = 1 'set the current column to one grdphone.Text = nameofperson 'place the name in the grid grdphone. exit this loop Input #1.Row = rowcounter grdphone. "Warning" Exit Sub 'go through any un-used grid rows 'and columns 'set the current row to rowcounter 'set the current column to colcounter 'empty the current cell 'end the procedure if no errors occurred 'start of error handling routine 'tell the user that an error occurred 'end the procedure End Sub The mnusave_click procedure should contain the code: Sub mnusave_Click () Dim filetosave Dim rowcounter 75 . then go no further currentfile = filetoget 'set the currentfile variable to the filename that we are about to load On Error GoTo cantopenit 'if an error occurs.Dim nameofperson Dim phone Dim gridrow Dim rowcounter Dim colcounter filetoget = InputBox("Enter the name of the file to open". currentfile) 'get a filename If filetoget = "" Then Exit Sub 'if the user hit the ‘cancel button.1) Then 'if we have exceeded the capacity of the grid grdphone.AddItem "".
iii)You will be notified of the number of blank formatted diskettes needed. 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. 76 . Hit the Next button. "Save File". .Text 'print the current cell's contents to the file Next colcounter Next rowcounter Close #1 'close the file Exit Sub 'if no errors occurred. and choose the Next button to continue. "Warning" Exit Sub End Sub 'start of error handling routine 'tell the user that an error occurred 'end the procedure The code generation phase of the project is complete. To create the distribution disk for this application: 1. Select any features needed by your application. 3.Row = rowcounter 'set the current row equal to rowcounter grdphone.Rows .Col = colcounter 'set the current column equal to colcounter Print #1. i) The SetupWizard will build the application’s executable file. Start Visual Basic’s SetupWizard by double clicking its icon. Run the application. 5. 2. Choose the Next button to continue. 4. end the procedure cantsaveit: MsgBox "Cannot Save File".1 'step through each row For colcounter = 0 To 1 'and column grdphone. go to the error handling routine Open filetosave For Output As #1 'open the file For rowcounter = 1 To grdphone.Dim colcounter 'get a filename from the user filetosave = InputBox("Enter Filename to Save". grdphone. currentfile) If filetosave = "" Then Exit Sub 'if the user hit the cancel button 'go no further currentfile = filetosave On Error GoTo cantsaveit 'set the currentfile variable to the filename 'that we are saving 'if an error occurs. Use the Select Project File button to browse for your application’s make file. Inform the SetupWizard of the disk drive and disk type to use when creating master distribution disks.
Use the Add Files button to add any special files required by your application. such as bitmaps. The SetupWizard will create the master distribution disks. 77 . INI files. 7. Hit the Next button. etc.6.
Appendix A A Sample Application Making Use of the File-System Controls 78 .
00 Begin 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 79 .The Form File VERSION 2.
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" Height = 255 Left = 3360 80 .
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 End End 81 .
doc" Case 3 filfiles.Pattern = "*.*" Case 1 filfiles.ListIndex Case 0 filfiles.• Code General Declarations 'all variables must be declared Option Explicit Sub cbofiletype_Click () 'change the pattern of the file list box 'according to the file type that the user 'selected Select Case cbofiletype.Pattern = "*.Pattern = "*.bas" End Select End Sub Sub cmdcancel_Click () End End Sub 82 .Pattern = "*.txt" Case 2 filfiles.
FileName Else pathandname = txtfilename End If 'the next statement may cause an error so we 'set an error trap On Error GoTo filelenerror 'get the file size of the file filesize = Str$(FileLen(pathandname)) 'display the size of the file MsgBox "The size of " + pathandname + " is " + filesize + " bytes" Exit Sub filelenerror: 'there was an error. "Error" Exit Sub End Sub Sub dirdirectory_Change () 'a directory was just selected by the user so 'update the path of the file list box 83 .Text = "" Then MsgBox "You must first select a file" Exit Sub End If 'make sure that path ends with backslash If Right$(filfiles.Path.Text = filfiles. 1) <> "\" Then Path = filfiles.Path + "\" Else Path = filfiles. so display error message and 'exit MsgBox "Cannot find size of " + pathandname.Sub cmdok_Click () Dim pathandname As String Dim filesize As String Dim Path ' if no file is selected then tell the user and 'exit this procedure If txtfilename.Path End If 'extract the path and name of the selected file If txtfilename.FileName Then pathandname = Path + filfiles. 48.
'accordingly filfiles.doc)" cbofiletype.AddItem "All files (*.Drive Exit Sub driveerror: 'an error occurred so tell the user and 'restore the original drive. MsgBox "Drive Error". cbofiletype.bas)" 84 .Path 'also update the lbldirname label lbldirname.AddItem "Doc Files (*.AddItem "Basic Files (*.txt)" cbofiletype.FileName End Sub Sub filfiles_DblClick () 'update the txtfilename text box 'with the file name that was just double clicked txtfilename.Text = filfiles.Path = dirdirectory.FileName 'execute the cmdok_click() procedure cmdok_Click End Sub Sub Form_Load () 'fill the cbofiletype combo box. "Error" Exit Sub End Sub Sub filfiles_Click () 'update the txtfilename text box with the file 'name selected txtfilename.Caption = dirdirectory.Path End Sub Sub drvdrive_Change () 'the next statement may cause an error so we 'set error trap.*)" cbofiletype.AddItem "Text files (*.Text = filfiles. On Error GoTo driveerror 'change the path of the directory list box to 'the new drive dirdirectory.Path = drvdrive. 48.
. all files) cbofiletype.'initialize the cbofiletype combo box to 'item #0 (i.ListIndex = 0 'update the lbldirnamelabel with the path lbldirname.Path End Sub 85 .e.Caption = dirdirectory.
215 ProjWinShow=2 IconForm="frmsize" 86 .VBX C:\WINDOWS\SYSTEM\CMDIALOG.VBX C:\WINDOWS\SYSTEM\MSOUTLIN.VBX C:\WINDOWS\SYSTEM\KEYSTAT.VBX C:\WINDOWS\SYSTEM\SPIN.VBX C:\WINDOWS\SYSTEM\CRYSTAL.VBX C:\WINDOWS\SYSTEM\THREED.VBX C:\WINDOWS\SYSTEM\PICCLIP.The Make File SIZE.VBX ProjWinSize=152.VBX C:\WINDOWS\SYSTEM\MSOLE2.VBX C:\WINDOWS\SYSTEM\GAUGE.FRM C:\VB\GRID.VBX C:\WINDOWS\SYSTEM\GRAPH.402.248.VBX C:\WINDOWS\SYSTEM\ANIBUTON.VBX C:\WINDOWS\SYSTEM\MSMASKED.VBX C:\WINDOWS\SYSTEM\MSCOMM.
Appendix B Visual Basic Derived Mathematical Functions 87 .
5708 hsin(x) = (exp(x) .5708 arccosec(x) = atn(x / sqr(x * x . Hyperbolic Tangent Inv. Hyperbolic Cosecant Inv.Function Secant Cosecant Cotangent Inverse Sine Inverse Cosine Inverse Secant Inverse Cosecant Inverse Cotangent Hyperbolic Sine Hyperbolic Cosine Hyperbolic Tangent Hyperbolic Secant Hyperbolic Cosecant Hyperbolic Cotangent Inv.1)) + (sgn(x) .5708 arccotan(x)=atn(x) + 1.1)) + sgn(sgn(x) .5708 arcsec(x) = atn(x / sqr(x * x .Hyperbolic Cotangent Logarithm Visual Basic Equivalent sec(x) = 1 / cos(x) cosec(x) = 1 / sin(x) cotan(x) = 1 / tan(x) arcsin(x) = atn(x / sqr( -x * x + 1) arccos(x) = atn(-x / sqr(-x * x + 1)) +1. Hyperbolic Cosine Inv. Hyperbolic Secant Inv.x)) / 2 harcsec(x) = log((sqr(-x * x + 1) + 1) / x) harccosec(x) = log((sgn(x) * sqr(x * x + 1) + 1) / x) harccotan(x) = log((x + 1) / (x .1)) harctan(x) = log((1 + x) / (1 .exp(-x)) hcotan(x) = (exp(x) + exp(-x)) / (exp(x) . Hyperbolic Sine Inv.1) * 1.exp(-x)) harcsin(x) = log(x + sqr(x * x + 1)) harccos(x) = log(x + sqr(x * x .exp(-x)) / 2 hcos(x) = (exp(x) + exp(-x)) / 2 htan(x) = (exp(x) .exp(-x)) / (exp(x) + exp(-x)) hsec(x) = 2 / (exp(x) + exp(-x)) hcosec(x) = 2 / (exp(x) .1)*1.1)) / 2 log base n (x) = log(x) / log (n) 88 .
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview.