3.1 The Visual Basic Programming Language
3.1 The Visual Basic Programming Language
3.1 The Visual Basic Programming Language
Ruby, originally called Tripod, was developed by Alan Cooper of Coactive Computing Corporation. Tripod was an application that allowed users to create their own computer interface in place of the Windows Desktop. After Cooper demonstrated Tripod to Bill Gates, Microsoft bought the rights to Tripod and renamed it Ruby. Cooper and the team of Mark Merker, Gary Kratkin, Mike Greary, and Frank Raab completed the final Ruby program for Microsoft in 1990.
isual Basic is used to create applications for Microsoft Windows. It includes tools that allow a programmer to create an application that has features similar to other Windows applications without having to write many lines of code.
Object-Oriented Programming
event-driven program
31
In this chapter, you will first learn how to create the interface of a Visual Basic application and then how to write the program code that tells the computer what the application should do. Throughout this text, you will learn how to create the application below and many others like it:
32
The Visual Basic IDE includes all the tools needed to create a Visual Basic application:
Screen Tips
Screen tips display the name of a button or control. A screen tip appears near the mouse pointer when pointing (not clicking) to a button or control.
Tool bar contains buttons that provide shortcuts to commonly performed actions. Tool box contains controls that are used to create objects. Project window is where the application interface is created. Project Explorer window lists the files in the current project. Properties window lists the properties values of an object. Form Layout window allows the applications interface to be positioned relative to the computer screen.
Review 1
Follow the instructions below to become familiar with the Visual Basic IDE.
33
label
Dragging the cross-hairs pointer displays the size of the object that will appear when the mouse button is released
command button
An object can also be added to the form by double-clicking a control. For example, a command button (the Done button) was added to the Hello World form by double-clicking on the CommandButton control ( ) in the Tool box. A command button object is something that the user can click on.
34
label properties
Each type of object has many different properties. Throughout the text, as objects are introduced, their most commonly used properties will also be discussed. So far, the label, command button, and form objects have been introduced. The label object has the properties: Name identifies an object and is used by the programmer. It is good programming style to begin label object names with lbl. Caption changes the text displayed in the label. In the graphic above, the Caption is Hello, world! Font is used to display a dialog box for changing the font, font style, and size of a labels Caption. Alignment changes the alignment of text in a labels Caption and can be set to left justify, right justify, or center.
The command button object has the properties: Name identifies an object and is used by the programmer. It is good programming style to begin command button object names with cmd. Caption changes the text displayed in the command button.
form properties
The form object has the properties: Name identifies an object and is used by the programmer. It is good programming style to begin form object names with frm. Caption changes the text displayed in the title bar.
programming style
The Name property is the only property that absolutely should be changed for each object in an application. The Name of an object should begin with the appropriate prefix and then be descriptive of the objects purpose. For example, the form Name for the Hello World application is frmHelloWorld. This name begins with the appropriate prefix (frm) and is descriptive of the forms purpose. Following proper naming conventions is good programming style.
35
Marquee Selection
Multiple objects can be selected using a technique called marquee selection. Selecting the Pointer control and then dragging the mouse pointer on the form creates a dashed-line box called a marquee. Creating this box around several objects and then releasing the mouse button selects all of the objects.
Review 2
Follow the instructions below to create the Hello World application interface described in the previous sections. If not already displayed, start Visual Basic and create a new Standard EXE project.
36
c.
If not already shown, scroll the properties list until the Caption property is displayed and then select Caption. d. Type Message to replace the current Caption and press Enter. Note the Title bar of the form now displays Message.
37
User Events
A user event is an action performed by the user. For example, a mouse click is a user event. Event procedures can be written for many different user events. For example, a command button click event procedure can be written for each command button.
38
Naming Objects
Event procedures require object names as part of the procedure name. For example, cmdDone_Click() is the name of the click event procedure for the Done command button. Therefore, objects must be appropriately named before creating any event procedures. Visual Basic will not automatically change an objects name in an event procedure if it is changed on the form after the code is created.
39
Review 3
Follow the instructions below to finish the Hello World application. The IDE and frmHelloWorld should still be displayed from the last review.
3 10
Review 4
Create a My Name application that displays your name centered, bold, and size 14 and a Done button that terminates the application when clicked. Use the Hello World application as a guide. The application interface should look similar to that shown on the right.
3 11
assignment
An assignment statement for changing property values uses the equal sign (=) to give the property on the left of the equal sign the value on the right of the equal sign and has the form: ObjectName.Property = Value where ObjectName is the objects Name, Property is a property name of the object, and Value is a valid property setting. Dot notation means that a period is used between the ObjectName and Property to access a property of an object. Each object property can be assigned only a valid property value. So far, the label, command button, and form objects have been introduced. The valid values of the label object properties are: Name cannot be changed at run time through assignment. Caption can be assigned text enclosed in double quotation marks ("). For example, the statement lblMessage.Caption = "Adios" will change the text of the lblMessage label to Adios. Font has several subproperties that are accessed using dot notation and each have their own set of valid property values. Size is a numeric value from 0 to 2048. Bold and Italic are either True or False. Name is a valid font name enclosed in double quotation marks. For example: lblMessage.Font.Size = 10 lblMessage.Font.Bold = True lblMessage.Font.Italic = False lblMessage.Font.Name = "Arial" Alignment can be assigned 0 (left justify), 1 (right justify), or 2 (center). For example, the statement lblMessage.Alignment = 0 will left justify the text in the lblMessage label. The valid values of the command button object properties are: Name cannot be changed at run time through assignment. Caption can be assigned text enclosed in double quotation marks ("). For example, the statement cmdCancelOrDone.Caption = "Done" will change the Caption of the cmdCancelOrDone button to Done. The valid values of the form object properties are: Name cannot be changed at run time through assignment. Caption can be assigned text enclosed in double quotation marks. For example, the statement frmUserApp.Caption = "My Application" changes the text in the title bar of the form to My Application.
Using AutoList
In the Code Editor window, typing an object name and then a dot (period) displays a list of the objects properties. This list is called an AutoList. For example, a label AutoList looks similar to:
AutoList
The arrow keys or mouse can be used to select a property name from the list and then the Tab key pressed to enter the property name after the dot. Pressing the spacebar enters the property name and a space after the dot. Typing an equal sign enters the property name and an equal sign after the dot.
Application Events
An application event is an event performed by the program. Event procedures can be written for many different application events. For example, the form load event procedure will be executed when the application starts.
3 12
Private Sub Form_Load() lblSample.Caption = "This text is centered." lblSample.Alignment = 2 End Sub Changing object property values in the Form_Load event procedure is an alternative to setting property values in the Properties window. Setting object properties through the Form_Load event is referred to as initializing the form. Initializing property values in the Form_Load is a way to document your program. It is easy to look at a printout of the Form_Load procedure to understand what objects are in an application without having to actually start Visual Basic and look at the form, its objects, and the Properties window.
Review 5
Follow the instructions below to complete the Alignment application described in the previous sections. The Visual Basic IDE should be displayed from the last review.
3 13
c.
Add the following statements to the Form_Load event procedure: Private Sub Form_Load() lblSample.Caption = "This text is centered." lblSample.Alignment = 2 'Center text in label (default) End Sub
3 14
File Types
An image control can display graphics in a bitmapped format. Bitmapped graphics are based on a grid, and each graphic is drawn by filling in the squares of the grid. Common bitmapped graphic file extensions are: BMP GIF JPEG Windows Bitmap Graphics Interchange Format Joint Photographic Experts Group
Name identifies the object and is used by the programmer. It is good programming style to begin image object names with img. Picture is used to display a dialog box for selecting the graphic to display in the image area. Stretch can be either True or False. When Stretch is True, the image is resized if the image box is resized. When Stretch is False, the image remains its original size if the image box is resized. Resizing the image box when stretch is False, crops, or hides, the part of the graphic that no longer fits in the image box. Visible can be either True or False. Visible is often set at run time to display (Visible = True) or hide (Visible = False) the graphic in the image box. When an image object is added to a form, it is displayed as a box:
Clicking on the ellipsis in the Picture property from the Properties list displays a dialog box where a graphic can be selected. The image box is then automatically resized to accommodate the selected graphic.
click event
A click event procedure is sometimes coded for each image object. The click event is executed when the user clicks on an image. This makes it possible to use image objects as buttons that perform an action when clicked.
3 15
Review 6
Follow the instructions below to add an image to the Hello World application. The IDE should still be displayed from the last review.
a. Move the label and command button objects to make room for the image object. b. In the Tool box, click on the Image control ( ) and then draw an image box that is approximately 0.5" by 0.5".
3 16
An expression is not enclosed in quotation marks because quotation marks indicate text. When the above statement is executed at run time, the Caption for lblAnswer will be changed to 314.
operator precedence
Visual Basic evaluates an arithmetic expression using a specific order of operations, or operator precedence. Exponentiation is performed first, multiplication and division next, and then addition and subtraction. Two operators of the same precedence, for example + and , are evaluated in order from left to right. For example, the expression 5 + 2 * 3 - 1 evaluates to 10 because multiplication is performed first and then the addition and subtraction. Operator precedence can be changed by including parentheses in an expression. The operations within parentheses are evaluated first. For example, the result of (5 + 2) * 3 is 21 because 5 and 2 were added before multiplication was performed. It is also good programming style to include parentheses when there is any ambiguity or question about the expression so a reader will not have any doubts about what is intended.
parentheses
programming style
3 17
compiler
Visual Basic also includes a compiler that translates the program code into a separate executable file. An executable file can be run independently of Visual Basic on any computer that uses Windows 95 or later. The Make command from the File menu is used to create an executable file. Note that if you are using the Working Model edition of Visual Basic included on CD with this text, executable files cannot be generated.
Review 7
For each of the following expressions, indicate the value that will be calculated by Visual Basic. If an expression is not legal, state why. a) 10 + 3 - 6 b) 15 * 2 + 4 c) 15 / 3 + 2 e) 15 * (2 + 4) f) "6 + 3 2"
d) 2^3 + 5 * 4
Review 8
The Circle application computes the area of a circle of radius 10. Follow the instructions below to complete the Circle application. Start the Visual Basic IDE if it is not already displayed.
3 18
6) SAVE, PRINT, AND THEN REMOVE THE PROJECT 7) EXIT VISUAL BASIC
From the File menu, select the Exit command. The Visual Basic IDE is removed from the screen.
Chapter Summary
object-oriented event-driven
Visual Basic is an object-oriented programming environment that is used to create event-driven applications for Microsoft Windows. Eventdriven programs wait for an event to occur and then respond to it by executing code in an event procedure. A Visual Basic application consists of an interface and program code. The interface is what appears on the screen when the application is running. The program code is the instructions that tell an applications objects how to behave when the user interacts with them. The Visual Basic IDE (Integrated Development Environment) includes all the tools needed to create a Visual Basic application. The IDE contains menus with commands for creating, saving, removing, opening, running, ending, and printing a project. The Tool bar has buttons for performing many of these tasks. The IDE also contains windows where the application interface is created, program code is written, and object properties are changed.
creating an object
A form object is used to hold other objects and is automatically added to a project when a project is created. An object is added to the form by clicking on a control in the Tool box and then dragging the cross-hairs pointer on the form or by double-clicking on a control.
3 19
A label object is used to display text or the result of an expression and is added to a form with the Label control ( ). A command button object is an object that can be clicked by the user. It is added to a form with the CommandButton control ( ). An image object is used to display a graphic and is added to a form with the Image control ( ). An object can be resized by clicking once on it to select it and then dragging a handle, and moved by selecting it and dragging it.
assignment
Properties define the appearance, behavior, position, and other attributes of an object. Every object should have its Name property changed to a descriptive name with the appropriate prefix. Object property values can be changed in the Properties window or through assignment statements that are executed at run time. An assignment statement uses the equal sign to give the property on the left of the equal sign the value on the right of the equal sign. Event procedures are executed in response to an event and are added to an applications form module in the Code Editor window. An event procedure is created by selecting the object name from the Object list. The Form_Load event procedure is used to execute code when a form is loaded, such as when an application started. The Unload statement terminates a program. Private indicates that a procedure cannot be accessed outside of the form module. Sub indicates the beginning of a procedure, and End Sub indicates the end of a procedure. Comments are used to explain and clarify program code for a human reader. A comment is included in code by preceding text with a single quotation mark ('). It is good programming style to include comments wherever code may be ambiguous or misleading. Visual Basic includes a set of built-in operators for exponentiation (^), multiplication (*), division (/), addition (+), and subtraction (). Arithmetic operators are used to form an expression. Expressions are evaluated using a specific operator precedence. Parentheses can be used to change operator precedence. The Visual Basic IDE includes an interpreter that automatically reads each line of program code as it is entered and highlights errors, and a compiler that translates the program code into a separate executable file. When creating a Visual Basic application, the application interface should be created first and the objects appropriately named before writing any code. The object list in the Code Editor window should be used to select the object event procedure.
event procedures
Form_Load Unload
comments
3 20
Vocabulary
Application interface What appears on the screen when a Visual Basic application is running. Assignment statement Uses the equal sign to give the object property on the left of the equal sign the value on the right of the equal sign. Body The statements in a procedure. Class Program code and data to create an object. Code Editor window The part of the IDE that displays the form module where program code is entered. Command button An object the user can click. Comment Information placed in a program to explain and clarify program code for a human reader. Comments are preceded by a single quotation mark. Compiler A program that translates program code into a separate executable file. Design time The time during which the application interface is being created. Dot notation property. Used in code to access an object Interface What appears on the screen when an application is running. Interpreter A program that automatically reads each line of program code as it is entered. Label An object used to display information. Menu bar The part of the IDE that contains the names of menus that contain commands. Object Has a visual representation and is used to reduce the complexity of graphics-based programs. OOP (Object-Oriented Programming) Uses classes to create objects and is widely used because it generates reusable, reliable code. Operator precedence The order in which operators are evaluated in an expression. Procedure See Event procedure. Program code Instructions that tell an applications objects how to behave when a user interacts with them. Project Visual Basic file that maintains all the files associated with an application, including the form and its objects and program code. Project Explorer window The part of the IDE that lists the files in the current project. Project window The part of the IDE that contains a form object and is where the interface is created. Properties window The part of the IDE that lists the properties values of an object. Property The part of an object that defines its appearance, behavior, position, and other attributes. Run time The time during which the application is being executed. Selecting Clicking once on an object to display its handles. Statement A line of code in a program that tells the computer what to do. Tool bar The part of the IDE containing buttons that provide shortcuts to commonly performed actions. Tool box The part of the IDE that contains controls that are used to create objects on a form object. Visual Basic Object-oriented programming environment used to create Windows applications.
Event A way in which the user can interact with an object. Event-driven program Waits until an event occurs before executing code. Event procedure Block of code executed in response to an event. Executable file A file that can be run independently of Visual Basic on any computer that uses Windows 95 or later. Expression Formed with arithmetic operators. Form An object used to hold other objects. Each interface has at least one form. Form Layout window The part of the IDE that allows the applications form position to be selected relative to the computer screen. Form module A file that contains the program code for a form. IDE (Integrated Development Environment) Contains all the tools necessary to create a Visual Basic application. Image An object that displays a graphic.
3 21
Visual Basic
^ Arithmetic operator used to perform exponentiation. * Arithmetic operator used to perform multiplication. / Arithmetic operator used to perform division. + Arithmetic operator used to perform addition. Arithmetic operator used to perform subtraction. () Used to change operator precedence in expressions. ' Precedes a comment. " Used to enclose text in an assignment statement. Also used to designate a font name in a font name assignment. = Used in an assignment statement to give the object property on the left of the equal sign the value on the right of the equal sign. Alignment Object property used to change the alignment of text in a labels Caption. Can be changed at run time. Bold Font subproperty that can be assigned either True or False. Can be changed at run time. Caption Object property used to change the text displayed in a Title bar, button, or label. Can be changed at run time. Code command Displays the form module for a form. Found in the View menu. CommandButton control Used to create a command button object. Found in the Tool box. End command Stops the current application. Found in the Run menu. The End button ( ) on the Tool bar can be used instead of the command. End Sub Required to end the Sub Statement. Exit command Closes the Visual Basic IDE. Found in the File menu. Font Object property used to display a dialog box for changing the font, font style, and size of an objects caption. Can be changed at run time. Image control Used to create an image object. Found in the Tool box. Italic Font subproperty that can be assigned either True or False. Can be changed at run time. Label control Used to create a label object. Found in the Tool box. Make command Creates an executable file. Found in the File menu. Me Used in place of the form name. Name Object property used to identify the object. Name Font subproperty that can be assigned a valid font name enclosed in quotation marks. Can be changed at run time. New Project command Creates a new project. Found in the File menu. Open Project command Opens an existing project. Found in the File menu. The Open Project button ( ) on the Tool bar can be used instead of the command. Picture Object property used to select a graphic. Print command Prints the interface and program code of an application. Found in the File menu. Private Indicates the procedure cannot be accessed outside of the form module. Remove Project command Removes the current project from the IDE. Found in the File menu. Save Project command Saves the current project. Found in the File menu. The Save Project button ( ) on the Tool bar can be used instead of the command. Size Font subproperty that can be assigned a numeric value from 0 to 2048. Can be changed at run time. Start command Runs the current application. Found in the Run menu. The Start button ( ) on the Tool bar can be used instead of the command. Stretch Object property that can be assigned True or False. Sub Declares a procedure. Unload Statement used to terminate a program. View Code button Clicked to view the form module. Found in the Project Explorer window. View Object button Clicked to view the form. Found in the Project Explorer window. Visible Object property that can be assigned True or False. Can be changed at run time.
3 22
Exercises
Exercise 1
Create an Address application that displays your name, city, and state in three separate labels. The application interface should look similar to:
Exercise 2
a) Create a School application that displays your schools name and mascot in two separate labels. The application interface should look similar to:
b) Modify the School application to display the Panther graphic and display the text Florida Panther when the image is clicked. The application interface should look similar to the following after clicking on the graphic:
3 23
Exercise 3
a) Create an Addition Properties application that displays the associative property of addition, (a+b)+c = a+(b+c), in a label. The application interface should look similar to:
b) Modify the program to display the associative property of addition after clicking on a button and the commutative property, a+b = b+a, when another button is clicked. The application interface should look similar to the following after clicking on the Commutative button:
Exercise 4
Create a Size Example application that displays a centered label with Small in size 10, Medium in size 14, or Large in size 18 depending on which button is clicked. The application interface should look similar to the following after clicking on the Medium button:
3 24
Exercise 5
Create a Style Example application that displays a centered, size 18 Style label that is only bold, only italic, or bold and italic depending on which button is clicked. The application interface should look similar to the following after clicking on the Bold and Italic button:
Exercise 6
Create a Font Example application that displays a centered, size 18 Font label that is either in Times New Roman or Arial font depending on which button is clicked. The application interface should look similar to the following after clicking on the Times New Roman button:
Exercise 7
Create a Hello and Good-bye application that displays Hello! or Good-bye! center aligned, size 18, and bold depending on which button is clicked. Include the Smiley graphic on the interface. The application interface should look similar to the following after clicking on the Hello button:
3 25
Exercise 8
Create a Calculations application that displays the result of a calculation after clicking on a button. The application interface should look similar to the following after clicking on the first command button:
Exercise 9
Create a Circle Circumference application that displays the circumference (2r) of a circle with radius 10. The application interface should look similar to the following after clicking on the Calculate button:
Exercise 10
Create a Rectangle Area and Perimeter application that displays the area (length * width) and perimeter (2l + 2w) of a rectangle of length 5 and width 3. The application interface should look similar to the following after clicking on the Calculate button:
3 26
Exercise 11
Create a Car Travel application that calculates and displays the number of kilometers per liter of gasoline a car gets if it travels 700 kilometers on a 70 liter tank of gas. The application should display the Car graphic on the interface when the Calculate button is clicked. The application interface should look similar to the following after clicking on the Calculate button:
Exercise 12
Create a Long Jump Average application that calculates and displays the average jump length of an athlete whose jumps were 3.3m, 3.5m, 4.0m, and 3.0m. The application interface should look similar to the following after clicking on the Calculate button:
Exercise 13
Create a Guitar Player application that displays the Guitar graphic and the name of your favorite guitar player when the graphic is clicked. The application interface should look similar to the following after clicking on the graphic:
3 27
3 28