3.1 The Visual Basic Programming Language

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Ruby

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.

3.1 The Visual Basic Programming Language


Visual Basic is based on the BASIC programming language developed in the 1960s by John Kemeny and Thomas Kurtz at Dartmouth University. BASIC stands for Beginners All-Purpose Symbolic Instruction Code and was used by Kemeny and Kurtz to teach programming to their students. In 1975, Bill Gates and Paul Allen developed a version of BASIC especially for the Altair personal computer. With the success of this new version of BASIC, Gates and Allen founded the Microsoft Corporation. BASIC then evolved to QuickBasic, a structured language that made programming easier for the rapidly growing number of personal computer users. In 1985, the Windows GUI was introduced. In 1992, Microsoft used QuickBasic and a program called Ruby to develop Visual Basic, an objectoriented programming (OOP) environment for creating Windows programs. OOP uses classes, which are program code and data, to create objects. In addition to program code, objects can have a visual representation such as a dialog box or a button and are used to reduce the complexity of developing graphics-based programs. Visual Basic programs are event-driven. An event is a way in which the user can interact with an object, such as using the mouse to click on a button in a dialog box. An event-driven program waits for an event to occur before executing any code, then only code for the current event is executed.

Object-Oriented Programming

event-driven program

3.2 A Visual Basic Application


interface program code
Each Visual Basic program, also called an 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.

Introducing Visual Basic

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:

The interface of a Visual Basic application

3.3 The Visual Basic IDE


creating a new project
The Visual Basic integrated development environment, or IDE, is used to create a Visual Basic application. A new application is created by first starting the Visual Basic IDE which displays the New Project dialog box:

Starting Visual Basic


Visual Basic can be started by clicking on the Start button on the Task bar, selecting Programs, and then selecting Visual Basic from the submenu. On some computers, selecting Visual Basic displays another submenu where the Visual Basic program can be selected, or there may be an icon on the Desktop that can be double-clicked to start Visual Basic.

The New Project dialog box


Selecting the Standard EXE icon and then the Open button in the New Project dialog box displays a project window in the IDE. If Visual Basic is already started, the New Project command (Ctrl+N) from the File menu can be used to create a new project. A project contains all the files for the application, including the form and its objects and program code.

32

An Introduction to Programming Using Microsoft Visual Basic

The Visual Basic IDE includes all the tools needed to create a Visual Basic application:

The Visual Basic IDE


Menu bar contains the names of menus that contain commands.

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.

1) START VISUAL BASIC


The New Project dialog box is displayed with the Visual Basic IDE behind it.

2) CREATE A NEW PROJECT


a. In the New Project dialog box, click on the Standard EXE icon if it is not already selected and then select Open. The New Project dialog box is removed and a Project window is displayed. b. Note the Tool box, the Project window, and the Project Explorer, Properties, and Form Layout windows.

Introducing Visual Basic

33

3.4 Adding Objects to a Form


form
Every Visual Basic application has at least one form. A form is a container object for other objects. For example, the Hello World application is a simple Visual Basic application with one form that contains a label and a command button. The Hello World interface appears similar to:

The Hello World application interface


design time
Objects are added to a form at design time. Design time refers to the time during which the application interface is being created. An object is added to a form by clicking on the desired control in the Tool box and then drawing the object. For example, the Hello World application has two objects on its form, a label and a command button. A label object is used to display information. The label was added to the form by selecting the Label control ( ) in the Tool box and then dragging the cross-hairs pointer:

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.

3.5 Object Property Values


An object has properties that define its appearance, behavior, position, and other attributes. These properties can be changed in the Properties window by selecting the objects name in the Object collapsible list and then selecting the property in the properties list. Next, a new value is typed or selected for the property. For example, in the Hello World application, the label displays Hello, world! because the label object was selected, then Caption was selected, and finally Hello, world! was typed:

34

An Introduction to Programming Using Microsoft Visual Basic

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.

command button properties

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.

Introducing Visual Basic

35

3.6 Resizing and Moving an Object


selecting an object
An object is selected by clicking on it to display handles. Once selected, dragging a handle resizes the object. Dragging a corner handle resizes both height and width:

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.

A selected object can be resized by dragging a handle


An object is moved by selecting it and then dragging it (not a handle) to a new location.

3.7 Saving a Project


A Visual Basic application is saved by selecting the Save Project command from the File menu or by clicking on the Save Project button ( ) on the Tool bar. When a project is first saved, both the form and the project must be given descriptive names. One good practice is to save the form using the same name as its Name property and then save the project using a name descriptive of the application. For example, the Hello World application should be saved as Hello World, and its form saved as frmHelloWorld.

3.8 Running a Visual Basic Application


run time
A Visual Basic application is run by selecting the Start command (F5) from the Run menu or by clicking on the Start button ( ) on the Tool bar. Run time refers to the time during which the application is being executed. A Visual Basic application can be run at any time during the development of the program. This allows testing of the application as it is being written. A running application can be terminated by selecting the End command from the Run menu or by clicking on the End button ( ) on the Tool bar.

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.

1) CHANGE THE PROPERTIES OF THE FORM OBJECT


The form object is currently selected because no other objects have been added to the application. The Properties window displays the properties of the selected object, the form. a. In the Properties window, select the Name property in the properties list if it is not already highlighted. (The Name property is enclosed in parentheses so it is first in the list.) b. Type frmHelloWorld and then press Enter to replace the current Name Form1. Note the Project window now displays the new name.

36

An Introduction to Programming Using Microsoft Visual Basic

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.

2) ADD A LABEL OBJECT


a. b. c. d. In the Tool box, click on the Label control ( ). Move the mouse pointer onto the form. Note that the pointer is now a cross-hairs pointer. Drag the cross-hairs pointer down and to the right to create a label object. Drag the label object (not a handle) so that is centered in the upper third of the form. If necessary, drag a handle to resize the object so that your form looks similar to:

3) CHANGE THE PROPERTIES OF THE LABEL OBJECT


a. Click once on the label object to select it, if it is not already selected. Handles are displayed. b. In the Properties window, change the Name property to lblMessage. c. Select the Alignment property. A down arrow is displayed indicating a list of options is available. d. Click on the Alignment down arrow to display a list of options and then select 2 - Center. Note the default text Label1 is now centered in the label object. e. Change the Caption property value to Hello, world! f. Select the Font property. An ellipsis is displayed () indicating a dialog box is available. g. Click on the Font ellipsis. The Font dialog box is displayed. h. In the Font style list, select Bold. i. In the Size list, select 18. j. Select OK. The options are applied to the label. Resize the label, if necessary, so that all the text is displayed.

4) ADD A COMMAND BUTTON OBJECT


a. In the Tool box, double-click on the CommandButton control ( ). A command button is placed on the form. b. Drag the command button object (not a handle) so that is centered in the lower third of the form so that your form looks similar to:

Introducing Visual Basic

37

5) CHANGE THE PROPERTIES OF THE COMMAND BUTTON OBJECT


a. Click once on the command button object to select it, if it is not already selected. Handles are displayed. b. In the Properties window, change the Name property to cmdDone. c. Change the Caption property value to Done. d. Select the Font property and then click on the ellipsis to display the Font dialog box. e. In the Size list, select 10 and then select OK.

6) SAVE THE HELLO WORLD PROJECT AND RUN THE APPLICATION


From the File menu, select the Save Project command. The Save File As dialog box is displayed. b. In the Save in entry box, select the appropriate folder. c. In the File name entry box, type frmHelloWorld if it is not already displayed and then select Save. The Save Project As dialog box is displayed. d. In the File name entry box, type Hello World and then select Save. e. On the Tool bar, click on the Start button ( ). The IDE is dimmed and the Hello World application is run. f. Click on the Done button. Nothing happens because program code has not yet been written to handle this. g. On the Tool bar, click on the End button ( ). The application is terminated and the IDE is displayed. a.

3.9 Objects and their Event Procedures


program code statement
An application, also referred to as a program, contains a set of instructions called program code that tells the computer how to perform a specific task. Each line of code is called a statement. Programs can contain tens to hundreds, even millions of lines of program code, or statements. An event procedure is a block of code that executes in response to an event. As discussed earlier, an event is a way in which the user can interact with an object, such as clicking a button. For example, an application that contains a command button needs to have a click event procedure for that button so that specific actions will be taken when the user clicks on the button. In a Visual Basic application, each form has a form module that is a container for program code. The area displaying the form module is referred to as the Code Editor window. The Code Editor window is viewed by double-clicking on the form or by selecting the Code command from the View menu. The Code Editor window can also be displayed by clicking on the View Code button ( ) in the Project Explorer window. The View Object button ( ) is clicked to view the form. Event procedures are coded in a form module. For example, the program code for the completed Hello World application appears like:

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

An Introduction to Programming Using Microsoft Visual Basic

The frmHelloWorld Code Editor window


Unload
The cmdDone_Click event procedure is executed when the user clicks on the Done button. This event procedure contains an Unload statement that removes the form from memory and ends the application. The Unload statement requires a form name. If the form to unload is the current form, then Me can be used in place of the form name. For example, the Unload frmHelloWorld statement above could be replaced by Unload Me. To add an event procedure, the desired object name is selected from the Object list and then a corresponding event is selected from the Event list. When an event procedure is added this way, it contains only two statements and has the form Private Sub ObjectName_Event() End Sub where ObjectName is the selected object name and Event is the selected event name. Private indicates that the procedure cannot be accessed outside of the form module. Sub declares the procedure and End Sub is required to end the Sub statement. Between these statements is the body of the procedure where statements that tell the application how to respond to the event procedure are added.

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.

3.10 Printing a Project


The interface and program code of an application are printed by selecting the Print command (Ctrl+P) from the File menu. Selecting Print displays a dialog box similar to:

Introducing Visual Basic

39

The Print dialog box


The Print What options in the dialog box are used to print either the form, code, or the form as text. Selecting OK prints the project.

3.11 Removing a Project from the IDE


When finished working with a project, it should be saved and closed. A project is closed by selecting the Remove Project command from the File menu. A dialog box is displayed if the form or project has been modified since it was last saved. Closing a project removes the project window from the IDE.

Review 3
Follow the instructions below to finish the Hello World application. The IDE and frmHelloWorld should still be displayed from the last review.

1) DISPLAY THE CODE EDITOR WINDOW


In the Project Explorer window, click on the View Code button ( ). The frmHelloWorld Code Editor window is displayed. b. In the Project Explorer window, click on the View Object button ( ). The form is once again displayed. c. In the Project Explorer window, click on the View Code button. The form module is again displayed. a.

2) ADD THE DONE BUTTON CLICK EVENT PROCEDURE


From the Object list in the Code Editor window (General is currently displayed), select cmdDone. A cmdDone_Click event procedure is added to the program code. b. Place the cursor in the blank line below Private Sub cmdDone_Click() if it is not already there. c. Press the Tab key and then type Unload frmHelloWorld. An Unload statement has been added to the click event procedure. Your procedure should look similar to: Private Sub cmdDone_Click() Unload frmHelloWorld End Sub a.

3) RUN THE APPLICATION


a. From the File menu, select Save Project or click on the Save Project button ( ) on the Tool bar. b. On the Tool bar, click on the Start button ( ). The IDE is dimmed and the Hello World application is run. c. Click on the Done button. The application is terminated because the click event procedure contains an Unload statement.

3 10

An Introduction to Programming Using Microsoft Visual Basic

4) PRINT THE PROJECT


a. From the File menu, select the Print command. The Print dialog box is displayed. b. Select the Current Module, Form Image, and Code options and then select OK. The application interface and program code are printed.

5) SAVE AND REMOVE THE PROJECT


a. Save the modified Hello World project. b. From the File menu, select the Remove Project command. The project is removed from the IDE.

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.12 Using Assignment to Change Property Values


In many applications, it is necessary to change the value of an objects property at run time. For example, the Alignment application below changes the Alignment and Caption properties of the label when the Left, Center, or Right buttons are clicked:

The Alignment application after clicking the Left button


Assignment is used to change the value of an object property at run time. For example, the cmdLeft_Click procedure of the Alignment application contains the following assignment statements: Private Sub cmdLeft_Click() lblSample.Caption = "This text is left justified." lblSample.Alignment = 0 End Sub

Introducing Visual Basic

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.13 The Form_Load Event Procedure


Event procedures can also be written for form events. The Form_Load event procedure is executed when a form is loaded into memory, such as when an application is started. For example, the following Form_Load procedure changes the Caption and Alignment of a label when the application is started:

3 12

An Introduction to Programming Using Microsoft Visual Basic

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.

3.14 Commenting Code


programming style
Comments are used to explain and clarify program code for a human reader. They have no effect on the way an application runs. The single quotation mark (') must begin a comment. It is good programming style to include comments wherever code can be ambiguous or misleading. For example, the statement below is easier to interpret with a comment: lblSample.Alignment = 0 'Left justify text in label

3.15 Opening a Project


An application is opened for editing by selecting the Open Project command (Ctrl+O) from the File menu or by clicking on the Open Project button ( ) on the Tool bar. After opening a project, it may be necessary to display the form by double-clicking on its name in the Project Explorer window. If folders are displayed in the Project Explorer window, doubleclicking on the Forms folder displays the names of the forms in the project.

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.

1) OPEN THE ALIGNMENT PROJECT


a. From the File menu, select the Open Project command. The Open Project dialog box is displayed. b. In the Look in entry box, select the appropriate folder. c. Click on Alignment and then select Open. The Alignment project is opened. d. If the Alignment form is not displayed, use the Project Explorer window to display the form name and then double-click on the name.

2) ADD THE FORM LOAD EVENT PROCEDURE


A default message and alignment can be displayed when the application is run by placing code in the Form_Load event procedure. a. In the Project Explorer window, click on the View Code button. The Code Editor window is displayed. b. From the Object list in the Code Editor window, select Form. A Form_Load event procedure is added to the code.

Introducing Visual Basic

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) ADD THE LEFT BUTTON CLICK EVENT PROCEDURE


a. From the Object list in the Code Editor window, select cmdLeft. A cmdLeft_Click event procedure is added to the program code. b. Add the following code so that the event procedure contains: Private Sub cmdLeft_Click() lblSample.Caption = "This text is left justified." lblSample.Alignment = 0 'Left justify text in label End Sub

4) ADD THE CENTER AND RIGHT BUTTON CLICK EVENT PROCEDURES


Create cmdCenter_Click and cmdRight_Click event procedures that contain the following code: Private Sub cmdCenter_Click() lblSample.Caption = "This text is centered." lblSample.Alignment = 2 'Center text in label End Sub Private Sub cmdRight_Click() lblSample.Caption = "This text is right justified." lblSample.Alignment = 1 'Right justify text in label End Sub

5) ADD THE DONE BUTTON CLICK EVENT PROCEDURE


Create a cmdDone_Click event procedure that contains the following code: Private Sub cmdDone_Click() Unload Me End Sub

6) SAVE THE PROJECT AND RUN THE APPLICATION


a. Save the modified Alignment project. b. Run the application. Click on each of the alignment command buttons to test the application. c. Click on the Done button to end the application.

7) PRINT AND THEN REMOVE THE PROJECT

3.16 Image Objects


An application that includes graphics can be more interesting and easier for a user to interact with. For example, a graphic of a globe could be added to the Hello World application to make it more interesting:

3 14

An Introduction to Programming Using Microsoft Visual Basic

The globe is added with the Image control


An image object is created using the Image control ( and has the properties: ) in the Tool box

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:

WMF Windows Metafile Format

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.

Introducing Visual Basic

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.

1) OPEN THE HELLO WORLD PROJECT


a. Open the Hello World project. b. In the Project Explorer window, double-click on frmHelloWorld if the Hello World form is not displayed.

2) ADD AN IMAGE OBJECT


Refer to the form below when placing and sizing the form and its objects as instructed in the steps following:

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) CHANGE THE PROPERTIES OF THE IMAGE OBJECT


a. b. c. d. e. f. Click once on the image object to select, if it is not already selected. Handles are displayed. In the Properties window, change the Name property to imgGlobe. Select the Picture property. An ellipsis is displayed indicating that a dialog box is available. Click on the Picture ellipsis. The Load Picture dialog box is displayed. In the Look in collapsible list, select the appropriate folder. Select Globe in the list of files displayed and then select the Open button. The globe graphic is placed in the image box. The image box was automatically resized to accommodate the globe.

4) CHANGE THE OBJECT SIZE


a. Drag a corner handle inward to reduce the size of the image. Release the mouse button and note that part of the image is hidden, or cropped, from view. b. Drag the corner handle outward until the entire image is again displayed. c. In the Properties window, change the Stretch property to True. d. Again drag a corner handle inward to reduce the size of the image. The image is resized along with the image box. e. Resize the image so that it is approximately 1" wide and 0.5" high and center it above the label.

5) CHANGE THE LABEL PROPERTIES


The label should not display any text when the application is started. a. Select the label object. b. In the Properties window, select the Caption property if it is not already selected and then delete all of the text in the property. The text displayed in the label object is removed.

3 16

An Introduction to Programming Using Microsoft Visual Basic

6) ADD THE IMAGE CLICK EVENT PROCEDURE


a. Display the Code Editor window. b. From the Object list in the Code Editor window, select imgGlobe. An imgGlobe_Click event procedure is added to the program code. c. Add the following statement so that when the user clicks the imgGlobe image the label displays the text Hello, world! Private Sub imgGlobe_Click() lblMessage.Caption = "Hello, world!" End Sub

7) TEST THE APPLICATION


a. Save the modified Hello World project. b. Run the application. Click on the globe to display Hello, world! c. Click on the Done button to end the application.

8) PRINT AND REMOVE THE PROJECT

3.17 Operators and Expressions


Visual Basic includes a set of built-in arithmetic operators including exponentiation (^), multiplication (*), division (/), addition (+), and subtraction (). Arithmetic operators are used to form an expression. An expression can be used anywhere a numeric value is allowed. For example, the assignment statement below includes an expression: lblAnswer.Caption = 3.14 * 10^2 'Display area of circle in label

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.18 Creating an Executable File


interpreter
Visual Basic uses an interpreter that automatically reads each line of program code as it is entered. If a statement has an error, Visual Basic highlights it immediately so that it can be corrected. When a program is run, the interpreter executes the code line-by-line and displays the output in the IDE.

Introducing Visual Basic

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.

3.19 Exiting Visual Basic


When finished working in Visual Basic, it should be exited by selecting the Exit command (Alt+Q) from the File menu. If a project is open and has not been saved since it was last modified, Visual Basic will display a warning dialog box before exiting.

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.

1) OPEN THE CIRCLE PROJECT


a. Open the Circle project. b. Display the Circle form if it is not already displayed.

2) RUN THE APPLICATION


Run the application. Click on the Calculate button. Nothing is displayed because an event procedure has not been written for the Calculate button click event. b. Click on the Done button. The application is terminated. a.

3) ADD THE CALCULATE BUTTON CLICK EVENT PROCEDURE


a. b. c. Display the frmCircle Code Editor window, if it is not already displayed. From the Object list in the Code Editor window, select cmdCalculate. A cmdCalculate_Click event procedure is added to the program code. The area of a circle is calculated by multiplying (3.14) and the radius of the circle squared (r2). Add the following statement to the cmdCalculate_Click event procedure: Private Sub cmdCalculate_Click() lblAnswer.Caption = 3.14 * 10^2 End Sub 'Display area of circle of radius 10 in label

4) SAVE THE PROJECT AND RUN THE APPLICATION


a. Save the modified Circle project. b. Run the application. Click on the Calculate button to test the application. 314 is displayed. c. Click on the Done button to end the application.

3 18

An Introduction to Programming Using Microsoft Visual Basic

5) CREATE AN EXECUTABLE FILE


If you are using the Working Model edition of Visual Basic included on CD with this text, you will not be able to complete this step. From the File menu, select the Make Circle.exe command. The Make Project dialog box is displayed. b. In the Save in entry box, select the appropriate folder. c. In the File name entry box, type Circle.exe, if it is not already displayed. d. Select OK. Visual Basic creates an executable Circle application called Circle. This file may be run from Windows like any other application. a.

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.

3.20 Visual Basic Programming Guidelines


Visual Basic programs are created using the Visual Basic IDE. Throughout this chapter, several programming style guidelines have been presented. In addition to using these style guidelines, there are a few other guidelines to follow when creating a Visual Basic application: Create the application interface first. Appropriately name all application objects before writing any code. Use the Object list in the Code Editor window to select the object event procedure.

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.

interface program code

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.

Introducing Visual Basic

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.

changing a property value

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

operator precedence interpreter compiler programming guidelines

3 20

An Introduction to Programming Using Microsoft Visual Basic

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.

Introducing Visual Basic

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

An Introduction to Programming Using Microsoft Visual Basic

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:

Introducing Visual Basic

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

An Introduction to Programming Using Microsoft Visual Basic

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:

Introducing Visual Basic

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

An Introduction to Programming Using Microsoft Visual Basic

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:

Introducing Visual Basic

3 27

3 28

An Introduction to Programming Using Microsoft Visual Basic

You might also like