Lab 5: Introduction to Visual Basic and User Interfaces

Tue Oct 23 11:24:16 EDT 2001

By the end of this lab, you will be able to:

You will also begin to develop some appreciation for how complex programming can be, how easy it is to make an error, and how frustrating it can be to find and fix an error. Don't get too frustrated! Ask a lab assistant for advice, take a short break, and try again.

This lab can only be done in the Friend Center clusters unless (very unlikely) you have Visual Basic installed on your own machine.

While typing a paper into your favorite word processor, or perhaps while playing the hottest new computer game, you might have at some point wondered: how do people create these great programs? The answer, of course, is with programming languages. Programming languages provide a way to express computer algorithms in a form that is both convenient for humans yet easily translated into a computer's machine language.

In class, we have studied the very low-level instructions that the computer itself understands, and talked about a variety of programming languages, much easier for people to use, that are translated by a program into machine instructions. There are many such languages, each with its own good and bad points, and often noisy adherents and detractors.

Visual Basic, the topic of this lab and the next one, is one of the most widely used languages. Part of the reason for its popularity is that it makes it quite easy to create graphical user interfaces, that is, the kind of interface with pull-down and pop-up menus, buttons, sliders, scroll bars, and the like. VB is not the best language for everything -- it isn't really meant for big programs, nor ones where speed of operation is paramount, and it only runs on Microsoft environments, which sometimes matters. But it's a very good tool for learning and for making prototypes.

Visual Basic is also embedded in other tools, providing a powerful and flexible extension mechanism: you can write VB programs that run within and control Word, Excel, Powerpoint, and other major software systems, augmenting their capabilities or tailoring them to your needs. This mechanism is also, unfortunately, at the heart of some common computer virus attacks, including the Melissa virus that struck in March, 1999, or the Anna Kournikova virus that struck a year later.

In this lab (and the next one) you will explore Visual Basic. VB is a descendant of the original BASIC language developed at Dartmouth in 1964 by John Kemeny ('47, *49) and Tom Kurtz (*56). We do not expect you to become full-fledged VB programmers, but you will do enough to get some understanding of what programs look like and what is involved in taking an algorithm and turning it into a precise program implementing that algorithm.

There is an enormous amount of Visual Basic information on the Web, and thousands of books. One useful place to look is at this tutorial on the VB environment. The Visual Basic environment that you will be running also has extensive built-in help, which you should become familiar with.


The Visual Basic Environment

An Overview

In this section, we'll give you a quick overview of Visual Basic. It's a bit daunting when one first turns it on, but in spite of the apparent complexity, it's pretty easy to get something running in short order.

Visual Basic has three major components:

The Visual Basic Language

A programming language fundamentally provides a way for you to tell a computer what to do, though often you have to spell things out in a lot of detail (which is one thing that makes programming a challenge). There are several kinds of statements:

Components and Building Blocks

VB comes from the factory with a large number of piece-parts that you can use to help create a program quickly; in fact, you couldn't do much without some of these, and it would be very time-consuming to create others from scratch. In effect, these component are like prefabricated components for houses -- windows, doors, kitchen cupboards -- that can be used even by comparatively unskilled users to create fairly polished looking products.

Some of the components have been around a long time; these include functions and subroutines for doing mathematical operations (square root, for example), reading information from files and writing it to files, manipulating strings of characters (like finding or replacing a word within a sentence).

The newer components are mostly focused on user interfaces: buttons, scrollbars, menus, text display areas. This is one aspect of the "visual" part of VB. These components are usually called objects; they have properties that can be set and changed (size, color, caption, etc.), methods that cause them to do something, and events or external stimuli, like pushing a button, that they respond to.

Finally, it is possible to include a vast range of components from the Windows environment itself; you can control a spreadsheet like Excel, or a word processor like Word, or a browser like Internet Explorer from within a VB program. We won't get into that here, but it gives some hint of the power that is near to hand. Much modern programming in fact involves assembling of large components in this way.

Integrated Development Environment

The VB development environment, which is the other half of "visual", is an interactive system that makes it fairly easy to draw an interface on the screen by dragging and dropping components (like buttons, for instance). The IDE also lets you set properties like size, color, position, captions, and so on by clicking on choices. The IDE helps you write your own code by creating templates that you fill in with the desired behaviors (this is where the real action is, generally), and also lets you manage and edit the text of the program; you can save things and restore them later.

You can run your program as you write it, in a controlled environment provided by VB, so that if something goes wrong, you are told quickly and often quite accurately what is wrong. And as we mentioned, there is an extensive help system to give rules and examples.

The Help System

VB is backed by an enormous collection of helpful information, though finding just the answer to your specific question is sometimes challenging. You can at any time select Help from the menubar that runs across the main VB window. This starts up the help system. If you are doing this for the first time, you should select Contents, then choose Visual Basic, then Getting Started.

Once you are using VB, you can access help for a specific entity on the screen by putting the cursor on it, then pushing the F1 key on the keyboard; this should bring up context-sensitive help.

The Simplest VB Program

This will all sound somewhat overwhelming, but it will become clearer. In this section, we're going to create the simplest possible VB program and run it. All it will do is display a single button, labeled Quit; when you press the button, the program will quit. But this trivial example will clarify much of the process, and let you move on to bigger things.

Start VB by Start / Programs / Microsoft Visual Studio 6.0 / Microsoft Visual Basic 6.0. It will first ask you what kind of project you want:

Choose "Standard EXE" if you are just starting; the result will look something like this:

Move your mouse slowly over the array of icons on the left side; each one raises a "tool tip" that tells what kind of object it is. Select "CommandButton" by pressing it, then move the mouse to the area labeled "Form1". The cursor will change to a large plus sign. Press your mouse button and sweep out a rectangle, then let go. The result will be like this:

You have just created a button whose name is Command1 that also has the caption Command1. You can move the button around or resize it if you're not happy with it. The size and position are properties that you can define and change at will. You can also change the name (we won't bother here) and the caption, which we will do.

Now type the word Quit and the caption on the button will change; notice that the entry for Caption in the Properties window near the right side is highlighted and changes at the same time as you type. You can use either to change the caption.

Now double-click the button (now labeled Quit). A new window will open up, called Project1 - Form1 (Code), and within it will be two lines of text:

Private Sub Command1_Click()

End Sub
This is an example of a code template, for a subroutine called Command1_Click that will be executed when the button Command1 is pressed or clicked. You just have to fill in the action that is to be performed. Type the word where the cursor is; your screen should now look like this:

Finally, the moment of truth. Near the middle of the toolbar at the top of the VB window, there is a small right-pointing blue triangle that will start your program. (The tool tip will say Start.) Press it, and you should see a window labeled Form1 with your Quit button in it:

It's pretty boring, but that is your program running (though it's mostly just waiting for you to press the button). Press the Quit button. That causes the event Command1_Click to occur, which calls your subroutine, which executes the statement End, which stops your program. So the window will go away, and you'll be back in VB.

(You can also stop your program by pressing the small blue square on the VB toolbar, near the Start triangle; this will prove useful if some other more complicated program doesn't work the way you expected. Try it to be sure.)

There's a lot more to it than this, of course, but mostly it's just endless elaboration on what you just did.


Elements of the Visual Basic Language

Overview

Here we will provide a very brief overview of some of the commands and syntax available in Visual Basic. This is by no means a complete reference, however, so you will want to look through some of the introductory material in the online Help system and also at some of the web pages we suggest.

Declaring Variables

A variable is a name that refers to a place in your program where information is stored; it ultimately corresponds to a location in memory. Variables can be of many types which specify how the value stored in that memory location should be interpreted. The main types for Visual Basic variables that you will use are: Integer (integer, like 123), Double (floating point number, that is, may have a decimal point and fractional part, like 3.1415), and String (a string or sequence of characters, like "hello").

Before you can use a variable in a Visual Basic program, you should first declare its type with the Dim statement. For example:

Dim age as Integer, height as Integer
Dim first_name as String, last_name as String
Dim GPA as Double

You can actually get by without declaring some variables, and VB will do its best to infer what you meant, but it's wiser to declare everything so that VB can check your program more carefully. If you add the line

	Option Explicit
to the beginning of your code, that will require you to include Dim statements for all variables. This option can also be set via Tools / Options / Editor / Require Variable Declaration; experienced VB programmers always set this option. Even though this makes slightly more work for the programmer, it greatly reduces the chance of a disastrous error that may be hard to find.

Comments

Comments provide a means for adding explanatory text to your program code, making it more understandable to human readers. In Visual Basic, comments are indicated by ' (a single quote character). Everything on a line after the ' will be ignored by the compiler. VB will color such commentary text green, so it's easy to spot.

Indentation and Space

Indentation to emphasize logical structure is a programming practice that makes your code easier for other humans to read and follow. It has no effect whatsoever on how VB processes your program, but it makes a lot of difference in how easy it is to read your own code. VB will help you format your programs properly, but it won't do the whole job; help it out, following the patterns we use below.

Operators and Expressions

Operators are special symbols like the + and - that you are familiar with from ordinary arithmetic; sometimes words are used because there is no natural character on the keyboard. An operator acts on the values or variables that it connects to compute a new value; an expression is just a legal combination of values and operators, like (my_ht+your_ht)/2. Some of the important operators are the following:

Operator Description
=
Assigns value on right to variable on left (e.g. next_year = year + 1)
+,-,*,/
Arithmetic: add, subtract, multiply, divide (integer)
&
Strings: append right string to end of left string
<,<=,>,>=
Comparators: less than, less than or equals, greater than, greater than or equals
=,<>
More comparators: equals, doesn't equal
and,or
Conditional AND (true if left and right expressions are both true) and conditional OR (true if either left or right expression is true)

Control Flow Statements

Control flow statements -- such as If, Do, and For -- determine what the program will do next, depending on the evaluation of some expression. Each of these statements is described below.

The If Statement

The If is used to select one of two groups of statements to do next: "If it's raining Then I will stay home Else I will go outside End If".
If condition Then
	action 
Else 
	other_action
End If

If the condition is true, then the action is taken, otherwise the other_action is taken. The action>s stand for one or more statements. The Else part is optional; sometimes the logic doesn't require it. There is also an ElseIf clause that you can use multiple times to describe a sequence of decisions:

If temperature > 212 Then
	print "boiling"
ElseIf temperature < 0 Then
	print "freezing"
Else 
	print "in between"
End If
The End If is always necessary.

The Do While ... Loop Statement

The Do statement is a loop that causes a group of statements to be repeated, usually while some condition is true, or until some condition becomes true: "Do While my room is a mess, pick up junk, throw it out, Loop".
Do While condition
	action
Loop

As long as the condition is true, then the action will be repeated. There is almost always a While condition attached to the beginning of a Do, to terminate the loop, but it can also appear at the end, or as Until if that reads more naturally.

So, for example, we might print a temperature conversion table like this:

Dim celsius as Double, fahrenheit as Double
fahrenheit = 0
Do While fahrenheit <= 212
	celsius = 5 / 9 * (fahrenheit - 32)
	print fahrenheit, celsius
	fahrenheit = fahrenheit + 1
Loop

The For ... Next Statement

The For ... Next statement is used for loops that step through a sequence of integer values, like 1 to 10.
For variable = start_value To end_value
	action
Next variable

This performs the action with the variable set in turn to start_value, start_value+1, up to end_value inclusive. This loop will print the same temperature values as the one above:

For fahrenheit = 0 to 212
	celsius = 5 / 9 * (fahrenheit - 32)
	print fahrenheit, celsius
Next fahrenheit

Subroutines and Functions

A subroutine is a chunk of program that can be used or called from other places in a program; it's a way to wrap up a useful computation in a package so it can be easily used just by naming it. The VB library includes a lot of subroutines that have already been written for you, and you can add more of your own. For example, we could write a subroutine to print a table of temperature conversions; wrapping the computation up in a subroutine makes it easier to change if necessary, and reduces clutter and confusion in the rest of the program. Here is such a subroutine:
Sub print_ftoc(low As Integer, high As Integer)
	Dim fahrenheit As Double, celsius As Double
	For fahrenheit = low to high
		celsius = 5 / 9 * (fahrenheit - 32)
		print fahrenheit, celsius
	Next fahrenheit
End Sub
It would be called as, for instance,
print_ftoc(0, 212)

A function is similar to a subroutine, except that it computes a value that can be used in an expression; mathematical functions like square root (which is called sqr in VB) are good examples.

Both subroutines and functions are usually defined with parameters, so that they can operate on different data values. Here's a function ftoc that converts temperatures from Fahrenheit to Celsius that could have been used in the examples above:

Function ftoc (fahrenheit As Double) As Double
	ftoc = 5 / 9 * (fahrenheit - 32)
End Function
This says that the function is named ftoc; it has an input parameter of type Double that will be referred to as fahrenheit within the function, and it returns a value of type Double.

Input and Output

Classic BASIC provided the print statement to display computed values, text, and so on; you can still use it in a VB program. Output from print goes to the current form; output from Debug.print goes to the Immediate window.

The other output statement that you will use regularly, especially when you're experimenting with your program, is MsgBox, which displays a dialog box. The simplest version is just

MsgBox "The end of the world is at hand."
which displays a dialog box with the message and an OK button. As a more elaborate example, this code:
Private Sub Disaster_dlg()
    Dim response As Integer
    response = MsgBox("Disaster!  Give up?", _
        vbYesNoCancel + vbQuestion)
    If response = vbYes Then
        End
    ElseIf response = vbNo Or response = vbCancel Then
        ' do some recovery
    End If
End Sub
creates this dialog box:

There is also a handy function called InputBox that pops up a dialog box with a prompt and a place for you to enter a value. The value is returned as a string; if the user hits the Cancel button, the string is empty (that is, "").

	Dim s As String
	s = InputBox("Enter some text")
	If s = "" Then
		Print "You didn't enter anything"
	Else
		Print "You entered " & s
	End If

Objects

Each object in a VB program, like a button or a textbox, presents its properties as variables that can be set or used in expressions. For example, to set the caption on a button called But1,
But1.Caption = "Quit!"
and to store that same caption in a variable,
Dim cap as String
cap = But1.Caption
We will see much more of this in the next section.


Graphical User Interface Components

Almost every computer now has a graphical user interface (GUI for short, pronounced gooey). Each GUI is made up of standard components that any program can use. You should have noticed many of these standard components while working on your labs. Almost all buttons, text fields, menus, etc., have the same look and feel, no matter what program you find them in. This is good for two reasons: software developers no longer have to design their own buttons and such, since these are provided for them, and the users of the programs are presented a more consistent interface. To make an interface for their programs, designers need only choose where to put the various items such as buttons, menus, and text fields.

Once the interface is designed and in place, the program looks complete: menus will drop down when you click on them, buttons will look pressed when you press them. The only thing wrong is that nothing happens when you press a button, or when you select a menu item. The button knows what to look like when you press it, but you never told it what to do when you press it. To assign actions to the various features of an interface, the program needs to interpret a set of automatically generated messages called events.

When you click on a button, the button generates an event, then sends the event to a routine called the event handler. In VB, events are handled by a subroutine whose name is a combination of the object that detected the event (like Command1) and the specific event type (like Click); thus the name will be, as we saw above, Command1_Click.

The event can be such things as "mouse passed over me", "someone pressed me", or "someone changed the text inside of me". For example, when you click a button But in a window, an event is generated that calls But_Click. Your task is to write statements that do the proper thing when such events are generated.

VB provides a large set of graphical components, of which we will use only a handful: Button, which we have already seen; Label for text display; and TextBox for displaying and reading text. In addition, the Form that contains the other objects is itself an object with properties, methods, and events, and we will manipulate those as well.

When you draw an object like a TextBox on a Form, VB displays a window listing the properties of that object and their current values; here is the Properties window for the original Form itself:

The Name comes first, and the others are listed alphabetically. Note especially the Caption, which is the title of the window, the Back(ground)color, the Font, and (not shown here) the ToolTipText. Almost all properties can be changed when the program is being created, by drawing on the screen or editing the information in the Properties window, or changed when the program is running, by assigning suitable values to the property. For example, you can change the background color to any color you want by

Form1.Backcolor = RGB(100, 150, 200)  
    ' red, green, blue components; each value between 0 and 255

In the next section you will have to create several objects and give them new names. Change the name before you change properties or generate any code because the name is used to identify the object.

Each object responds to a set of events; you can determine what these are by double-clicking on the object to raise a code window, then pull down the list of events at the top right:

Each of these will give you a template for the corresponding subroutine so you can easily write the code to be executed when the event occurs.

You will also notice that VB will raise a menu of legitimate properties as you type, narrowing the list as you type more of the word. If you see the one you want, you can select it with the mouse or hit Tab and VB will complete the typing for you. This popup menu is often very helpful for reminding you of available properties.


Writing your own Visual Basic Program

Your assignment

Your assignment is to implement a program that will play the old guessing game "I'm thinking of a number between 1 and 100. What is it?". Our version looks like this:

You can make yours look much more professional if you wish, once you have it working properly, by laying out the components anywhere and using any sizes, fonts, and colors that you like.

What your program should do

Your program should do the following:

Draw the Interface

Each component of the user interface has a name in the VB program. The screen shot above has seven components. There are two TextBoxes for the range and the guess; you must call yours range and guess. There are three Labels, for "I'm thinking of a number...", "What's your guess?", and "Too high". You should call them thinking, whatsyours, and result. Finally, there are two buttons, newgame and quit.

You must use these names for components so the lab assistants can help you and so we can grade.

Using the icons in the toolbox area on the left side of the VB window, draw the 7 components above on the Form called Form1. As you draw each one, immediately change its name to the corresponding name given above by editing the Name field in the Properties window on the right side of the VB window.

Change the Caption fields of the three Labels to "I'm thinking of a number between 1 and", "What's your guess?", and nothing. Change the captions on the two buttons.

Change the Text property of the range Textbox to 100, and of the guess Textbox to nothing.

Finally, change the Caption property of Form1 to something that includes your name.

Saving your work

There's a fair amount of work in this lab, and you don't want to lose it. So you should save your work every few minutes, especially after you make significant changes or additions. Choose File / Save Project As.... You will offered the chance to save Form1.frm; save it as guess.frm on your H: drive. Similarly, save Project1.vbp as guess.vbp. (These are just text files and you can look at them with Notepad.) You can then restart this at some later time by opening the .vbp file with File / Open Project....

You can also print files if you like to keep a paper trail.

Add the Statements for the Program

Program statements are placed in the Code window, which is often hiding behind the Form window. You can switch back and forth between Code and Form using the entries under the View menu item. You can also freely edit anything in the Code window, especially to delete unwanted items and blank lines. Your entire program is there, though you may have to scroll up and down to see it.

You will need a variable to hold the secret random number that the user is to guess. Since this value will be needed by at least two subroutines of your program, it must be declared at the beginning of your program, before any of the Sub definitions. Go to the code window and type this line:

	Dim secretnumber As Integer

Quit Button

Now you can start to add some functionality. First, make the Quit button work. Go to the Code window and select quit from the drop-down list at the top left; this will create a template for subroutine quit_Click. Type in the VB statement that causes the program to terminate. Test the program so far.

New Game Button

Go to the Code window and select newgame from the drop-down list at the top left; this will create a template for subroutine newgame_Click. You should just copy this line and paste it into the template in your VB code window.
	secretnumber = Int(rnd * range) + 1
The built-in function Rnd produces a different (pseudo-)random number between 0 and 1 each time it is called. The rest of this line converts the characters in the range Textbox into an integer value, then scales up the random number to a random integer between 1 and the range value.

Add a MsgBox statement after this line to display the secret number, then test this part of the program.

Rnd by itself produces a sequence of apparently random numbers, but from a given starting point it's always the same sequence. To get a different sequence (randomized from the time of day), add the line

	Randomize
before the secretnumber = rnd... line. Then the game will be different every time you play it. (Do not add this line until you are sure your program is working; it's easier to debug the program if it behaves the same way each time it runs.)

Fetching the Guess

The next step is to fetch the guess that your user has just typed in. This is a bit tricky, since you must be sure that the user has finished typing: you don't want to do anything until the user pushes the Return or Enter key.

We have provided a function that causes the guess TextBox to call a subroutine checkguess when the user presses the Enter key:

Private Sub guess_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = 13 Then  ' 13 is the ASCII decimal value for newline
        checkguess        ' you have to write this subroutine...
    End If
End Sub
Copy this and paste it into your VB code window, right after a line that says End Sub.

Checking the User's Guess

You have to write the checkguess subroutine, which checks the guess to see if it is correct. To start writing this function, just type Sub checkguess in the code window after an End Sub line; when you push Enter, a new subroutine template will appear and you can insert your code into it.

The user's guess is in the Textbox guess. Add this line as the first line of subroutine checkguess:

	userguess = CInt(guess)
This will store the user's guess in the variable userguess.

Before you do anything else, verify that you can properly read the user's guess by using a MsgBox to display userguess.

Now you can go on to the real logic of the program: is the user's guess too high, too low, or just right? Your task now is to fill in the last few lines of checkguess to do this test and display the right message as the Caption of the result Label. This will require some If statements that compare the guess to the secret number; look back at the discussion of control flow if you need to.

To set the caption, you will need lines like this one:

	result.caption = CStr(userguess) & " is too high"
CStr is another built-in VB function that produces a sequence of characters from a numeric value, and the & appends one sequence of characters to the end of another. You will need these here to get neat-looking output.

The very last step of checkguess is to clear the guess textbox so it's ready to accept the next guess. You can do this by assigning a string of no characters to it; that's written as "" (two adjacent double-quote characters).

One Step at a Time

Since this is your first Visual Basic program you are liable to make mistakes. This is not as bad as it sounds -- if you are methodical, finding these mistakes (or debugging) will not be too hard. A good idea is to write small sections at a time, and test as you go; this is what we have been suggesting above. This approaches makes it much easier to find what section of your code has the error.

Use MsgBox statements to display results as your computation proceeds, or just to verify that your program is going where you think it is. These are easy to add and help narrow down problems quickly.

Another tip for this problem is to display the correct answer right away, until you know the program is working. It's hard to debug a program that generates a different random value each time it runs!

More on CStr and CInt

You have already learned a few ways that the computer can store numbers, in numeric form or as a series of characters. Programmers often need to convert between these two formats and most programming languages provide an easy way to do so. In this lab you will use two conversion functions that are a standard part of VB: CStr(num) produces the numeric value of num as the equivalent string of characters so it can be inserted in a TextBox or similar place, and CInt(str) computes the numeric value of the string of characters str so it can be used in an arithmetic computation.

Inside your program text values must appear inside quotes (e.g., "What's your guess?"), The & sign is used to attach two text strings to form a new one (e.g., "Hi " & "There" is the same as "Hi There").

Putting all these together, if you want your MsgBoxes to display both numbers and characters, you will need to use statements like this:

	MsgBox "The user's guess is " & CStr(userguess)

Comments

Comments are a part of the code not looked at by VB when it is running your program. Comments are used to make the code more readable for other people that may have to work on it, or to remind you of what you were thinking when you write a particular line of code. In Visual Basic comments start with ' and go until the end of a line. We have included comments in some of the code above; you are advised to include comments of your own to remind yourself and others of what you are doing. You might also find it helpful to leave any MsgBox statements in the program, but "commented out" so they can be easily restored if something goes wrong.

Finishing up and shutting down

Copy your files to your Unix Account

You will first be offered the chance to save Form1.frm, which contains your VB Form1 objects and code.

You will next be offered the chance to save the VB project itself in Project1.vbp.

Both of these are ordinary text files that you can look at and even change with Notepad.

Submitting your work by email

It is a very good idea to check with one of the lab assistants to make sure that they have seen your project in its working state, that your files have been properly saved in your Unix account, and that you are sending the right files for grading. Mail the files to yourself as well and be sure that they have arrived safely. Do all of these before you log out.
Every year, several people lose all of their work because they have not followed these instructions or heeded these warnings. Please don't be one of this year's victims!

If you've completed the lab, sent your email to cs109@princeton.edu or cs111@princeton.edu and transferred your work to your Unix account, then you are finished.