Lucky Seven: Your First Visual Basic Program
The Windows-based application you’re going to construct is Lucky Seven, a game program that simulates a lucky number slot machine. Lucky Seven has a simple user interface and can be created and compiled in just a few minutes using Visual Basic. (If you’d like to run a completed version of Lucky.exe before you start, you can find it in the Vb6SbsLess02 folder on your hard disk.) Here’s what your program will look like when it’s finished:
Programming Steps
The Lucky Seven user interface contains two command buttons, three lucky number windows, a graphic of a stack of coins, and the label Lucky Seven. These elements were produced in the program by creating seven objects on the Lucky Seven form and then changing several properties for each object. After the interface was designed, program code for the Spin and End command buttons was added to the program to process the user’s button clicks and produce the random numbers. To re-create Lucky Seven, you’ll follow three essential programming steps in Visual Basic: creating the user interface, setting the properties, and writing the program code. The process for Lucky Seven is summarized in the table on the following page.
Programming step | Number of items |
1. Create the user interface. | 7 objects |
2. Set the properties. | 10 properties |
3. Write the program code. | 2 objects |
Another way to think about the Lucky Seven program is to use the following algorithm, or list of programming steps. Creating an algorithm can be a useful starting point when developing a program.
Creating the User Interface
In this exercise you’ll start building Lucky Seven by creating a new project and then using controls in the toolbox to construct the user interface.
Create the user interface
- On the File menu, click the New Project command.
You start a new programming project by clicking the New Project command on the File menu.
- Click OK to create a standard 32-bit Visual Basic application.
Now you’ll enlarge this form, and then you’ll create the two buttons in the interface.
- Position the mouse pointer over the lower-right corner of the Form window (not the Project Container window) until the mouse changes into a sizing pointer, and then increase the size of the form to make room for the objects in your program.
To see the entire form without obstruction, resize the Project Container window to remove the scroll bars and move or close the Properties window, the Project window, and the Form Layout window.
Now you’ll practice a command button object on the form.
tip
Confused by all this resizing? Don’t sweat it. You’re working with two windows here: the Project Container window and the Form window (which fits inside the Project Container window). The troublesome part is that you resize each window by using the resizing pointer in the lower-right corner of the frame, and these two corners tend to overlap a bit. To get more real estate to design your projects, you may want to run Windows in 800 x 600 mode, which you can do by clicking the Windows desktop with the right mouse button, clicking Properties, clicking the Settings tab, and then moving the Desktop Area slider to 800 x 600.
- Click the CommandButton control in the toolbox, and then place the mouse pointer over the form.
CommandButton control
The CommandButton control is selected, and the mouse pointer changes to crosshairs when it rests on the form. The crosshairs are designed to help you draw the rectangular shape of a command button. When you hold down the left mouse button and drag, the command button object takes shape and snaps to the grid formed by the intersection of dots on the form.
Try creating your first command button now.
- Move the mouse pointer close to the upper-left corner of the form, hold down the left mouse button, and then drag down and to the right. Stop dragging and release the mouse button when you have a command button similar to the one shown here:
A command button with selection handles appears on the form. The button is named Command1, the first command button in the program. (You might make a mental note of this button name—you’ll see it again later when you write your program code.)
You can move command buttons by dragging them with the mouse and you can resize them by using the selection handles whenever Visual Basic is in design mode (whenever the Visual Basic programming environment is active). When a program is running, however, the user will not be able to move interface elements unless you have changed a special property in the program to allow this. You’ll practice moving and resizing the command button now.
Move and resize a command button
- Drag the command button to the right by using the mouse.
- Position the mouse pointer on the lower-right corner of the command button.
The grid helps you design your user interface.
- Enlarge the object by holding down the left mouse button and dragging the pointer down and to the right.
- Use the sizing pointer to return the command button to its original size, and then move the button back to its original location on the form.
Now you’ll add a second command button to the form, below the first button.
Add a second command button
- Click the CommandButton control in the toolbox.
CommandButton control
- Draw a command button below the first button on the form. (For consistency, create a command button of the same size.)
- Move or resize the button as necessary after you place it. If you make a mistake, feel free to delete the command button and start over.
You can delete an object by selecting the object on the form and then pressing Del.
Add the number labels
Now add the labels used to display the numbers in the program. A label is a special user interface element designed to display text, numbers, or symbols when a program runs. When the user clicks the Lucky Seven program’s Spin button, three random numbers appear in the label boxes. If one of the numbers is a seven, the user hits the jackpot.
- Click the Label control in the toolbox, and then place the mouse pointer over the form.
Label control
- Create a small rectangular box like the one shown below.
- Click the Label control, and then draw a label box to the right of the first label.
- Click the Label control again and add a third label to the form, to the right of the second label.
tip
As you create labels in this exercise, take a look at the pop-up box that appears next to the labels as you draw them. This box, which contains horizontal and vertical measurements, is called a sizing box. The numbers give the horizontal and vertical dimensions, respectively, of the object you are creating. The numbers are in units of measure called twips; a twip is one-twentieth of a point. (A point is 1/72 inch, so a twip is 1/1440 inch.) You can use the sizing box to compare the relative sizes of objects you’re creating. After you create the object, the same information is also displayed on the right side of the toolbar.
Now you’ll use the Label control to add a descriptive label to your form. This will be the fourth and final label in the program.
- Click the Label control in the toolbox.
- Create a larger rectangle directly below the two command buttons.
When you’ve finished, your four labels should look like those in the following illustration. (You can resize the label objects if they don’t look quite right.)
Now you’ll add an image box to the form to display the stack of coins the user wins when he or she draws a seven and hits the jackpot. An image box is designed to display bitmaps, icons, and other artwork in a program. One of the best uses for an image box is to display a piece of Visual Basic clip art.
Add an image
- Click the Image control in the toolbox.
Image control
- Using the Image control, create a large rectangular box directly beneath the three number labels.
This object will be called Image1 in your program; you’ll use this name later in the program code.
Setting the Properties
As you discovered in Lesson 1, you can change properties by selecting objects on the form and changing their settings in the Properties window. You’ll start setting the properties in this program by changing the caption settings for the two command buttons.
Set the command button properties
- Click the first command button (Command1) on the form.
- Double-click the Properties window title bar.
The Properties window lists the settings for the first command button. These include settings for the background color, caption, font height, and width of the command button.
- Double-click the Caption property in the left column of the Properties window.
- Type Spin and press Enter.
- Open the object drop-down list box at the top of the Properties window.
- Click Command2 (the second command button) in the list box.
- Double-click the current Caption property ("Command2"), type End, and then press Enter.
tip
Using the object drop-down list box is a handy way to switch between objects in your program. You can also switch between objects on the form by clicking each object.
Set the number label properties
- Click the first number label, and then, holding down the Shift key, click the second and third number labels. (If the Properties window is in the way, move it to a new place.)
To select more than one object on a form, hold down the Shift key while clicking the objects.
tip
Because more than one object is selected, only those properties that can be changed as a group are displayed in the Properties window. You’ll change the Alignment, BorderStyle, and Font properties now so that the numbers that appear in the labels will be centered, boxed, and identical in font and point size.
- Click the Alignment property, and then click the drop-down list box arrow that appears to the right.
- Click the 2 - Center option.
Now you’ll change the BorderStyle property.
- Click the BorderStyle property, and then click the drop-down list box arrow that appears to the right.
- Click 1 - Fixed Single in the list box to add a thin border around each label.
- Double-click the Font property in the Properties window.
- Change the font to Times New Roman, the font style to Bold, and the point size to 24, and then click OK.
Now you’ll delete the three captions so that the boxes will be empty when the program starts. (Your font selections will remain with the labels because they are stored as separate properties.) To complete this operation, you’ll first need to select each of the labels individually.
- Click the form to remove the selection handles from the three labels, and then click the first label.
- Double-click the Caption property, and then press Del.
- Delete the captions in the second and third labels on the form.
You’ve finished with the first three labels. Now you’ll change the Caption, Font, and ForeColor properties of the last label.
Set the descriptive label properties
- Click the fourth label object on the form.
- Change the Caption property to "Lucky Seven".
- Double-click the Font property, and use the Font dialog box to change the font to Arial, the font style to Bold, and the point size to 20. Click OK.
Now you’ll change the foreground color of the text.
- Double-click the ForeColor property in the Properties window.
- Click the Palette tab, and then click the box containing dark purple.
The Image Box Properties
The image box object will contain the graphic of the stack of coins in your program. This graphic will appear when the user hits the jackpot (that is, when at least one seven appears in the number labels). You need to set the Stretch property to accurately size the graphic; the Picture property, which specifies the name of the graphics file to be loaded into the image box; and the Visible property, which specifies the picture state at the beginning of the program.
Set the image box properties
- Click the image box object on the form.
- Click the Stretch property in the Properties window, click the drop-down list box arrow, and then click True.
- Double-click the Picture property in the Properties window.
- Navigate to the Vb6Sbs folder in the Load Picture dialog box.
- Double-click the Less02 folder.
- Select the file Coins.wmf in the dialog box, and then click Open.
Now you’ll change the Visible property to False so that the coins will be invisible when the program starts. (You’ll make them appear later with program code.)
- Click the Visible property. Click the Visible drop-down list box arrow.
- Click False to make the image invisible when the program starts.
- Double-click the Properties window’s title bar to return it to the docked position.
Writing the Code
Now you’re ready to write the code for the Lucky Seven program. Because most of the objects you’ve created already "know" how to work when the program runs, they’re ready to receive input from the user and process it automatically. The inherent functionality of objects is one of the great strengths of Visual Basic—once objects are placed on a form and their properties are set, they’re ready to run without any additional programming. However, the "meat" of the Lucky Seven game—the code that actually calculates random numbers, displays them in boxes, and detects a jackpot—is still missing from the program. This computing logic can be built into the application only by using program statements—code that clearly spells out what the program should do each step of the way. Because the program is driven by the Spin and End buttons, you’ll associate the code for the game with those buttons. The Code window is a special window in the programming environment that you use to enter and edit Visual Basic program statements.
Reading Properties in Tables
In this lesson, you’ve set the properties for the Lucky Seven program step by step. In future lessons, the instructions to set properties will be presented in table format unless a setting is especially tricky. Here are the properties you’ve set so far in the Lucky Seven program in table format, as they’d look later in the book.
Object | Property | Setting |
Command1 | Caption | "Spin" |
Command2 | Caption | "End" |
Label1, Label2, Label3 | BorderStyle Alignment Font Caption | 1 – Fixed Single 2 – Center Times New Roman, Bold, 24-point (Empty) |
Label4 | Caption Font ForeColor | "Lucky Seven" Arial, Bold, 20-point Dark purple (&H008000808) |
Image1 | Picture Stretch Visible | "Vb6SbsLess02coins.wmf" True False |
In the following steps, you’ll enter the program code for Lucky Seven in the Code window.
Use the Code window
- Double-click the End command button on the form.
If the window is smaller than the one shown above, resize it with the mouse. (The exact size is not that important because the Code window includes scroll bars that you can use to examine long program statements.)
Inside the Code window are program statements that mark the beginning and the end of this particular Visual Basic subroutine, or event procedure, a block of code associated with a particular object in the interface:
Private Sub Command2_Click()
End Sub
The body of a procedure always fits between these lines and is executed whenever a user activates the interface element associated with the procedure. In this case, the event is a mouse click, but as you’ll see later in the book, it could also be an event of a different type.
- Type End, and press the Down arrow key.
You use the program statement End to stop your program and remove it from the screen. The Visual Basic programming system contains several hundred unique keywords such as this, complete with their associated operators and symbols. The spelling of and spacing between these items are critical to writing program code that will be accurately recognized by the Visual Basic compiler.
tip
Another name for the exact spelling, order, and spacing of keywords in a program is statement syntax.
- Move the cursor to the beginning of the line with the End statement in it, and press the Spacebar four times.
Write code for the Spin button
- Open the Object drop-down list box in the Code window.
- Click Command1 in the list box.
By default, Visual Basic displays all the event procedures for a form in one window, so you can easily switch back and forth between them. (A horizontal line appears between the procedures so you can keep them apart.) Alternatively, you can view one procedure per window by clicking the tiny Procedure View button in the bottom-left corner of the Code window. To see all the procedures again in one window, click the Full Module View button located just to the right of the Procedure View button.
Although you changed the caption of this button to "Spin", its name in the program is still Command1. (The name and the caption of an interface element can be different to suit the needs of the programmer.) Each object can have several procedures associated with it, one for each event it recognizes. The click event is the one we’re interested in now because users will click the Spin and End buttons when they operate the program.
- Type the program lines shown on the following page between the Private Sub and End Sub statements, pressing Enter after each line and taking care to type the program statements exactly as they appear here. (The Code window will scroll to the left as you enter the longer lines.) If you make a mistake (usually identified by red type), delete the incorrect statements and try again.
As you enter the program code, Visual Basic formats the text and displays different parts of the program in color to help you identify the various elements. When you begin to type a property, Visual Basic also displays the available properties for the object you’re using in a list box, so you can double-click the property or keep typing to enter it yourself. If Visual Basic displays an error message, you may have misspelled a program statement. Check the line against the text in this book, make the necessary correction, and continue typing. (You can also delete a line and type it from scratch.) Readers of previous editions of this book have found this first typing exercise to be the toughest part of the lesson—"But Mr. Halvorson, I know I typed it just as written!"—so please give this program code your closest attention. I promise you, it works!
Image1.Visible = False ‘ hide coins
Label1.Caption = Int(Rnd * 10) ‘ pick numbers
Label2.Caption = Int(Rnd * 10)
Label3.Caption = Int(Rnd * 10)
‘if any caption is 7 display coin stack and beep
If (Label1.Caption = 7) Or (Label2.Caption = 7) _
Or (Label3.Caption = 7) Then
Image1.Visible = True
Beep
End If
When you’ve finished, the Code window should look like the following:
A Look at the Command1_Click Procedure
The Command1_Click procedure is executed when the user clicks the Spin button on the form. The procedure uses some pretty complicated statements, and because I haven’t formally introduced them yet, the whole thing may look a little confusing. However, if you take a closer look you’ll probably see a few things that look familiar. Taking a peek at the contents of the procedures will give you a feel for the type of program code you’ll be creating later in this book. (If you’d rather not have a look, feel free to skip to the next section, "Saving the Program.")
The Command1_Click procedure performs three tasks: it hides the coin stack, creates three random numbers for the label windows, and displays the coin stack when the number seven appears. Let’s look at each of these steps individually.
The Command1_Click procedure is the heart of the Lucky Seven program.
The first task in the procedure is accomplished by the line
The second part of the first line (the part displayed in green type on your screen) is called a comment. Comments are explanatory notes included in program code following a single quotation mark (‘). Programmers use comments to describe how important statements work in a program. These notes aren’t processed by Visual Basic when the program runs; they exist only to document what the program does. You’ll want to use comments often when you write Visual Basic programs to leave a "plain English" record of what you’re doing.
Comments describe what program statements do.
The next three lines handle the random number computations. The Rnd function in each line creates a random number between 0 and 1 (a number with a decimal point), and the Int function multiplies the numbers by 10 and rounds them to the nearest decimal place. This computation creates random numbers between 0 and 9 in the program. The numbers are then assigned to the Caption properties of the first three labels on the form, and the assignment causes the numbers to be displayed in boldface, 24-point, Times New Roman type in the three label windows.
The last group of statements in the program checks whether any of the random numbers is seven. If one or more of them is, the stack of coins is made visible on the form and a beep announces a jackpot. Each time the user clicks the Spin button, the Command1_Click procedure is called and the program statements in the procedure are executed.
Saving the Program
Now that you’ve completed the Lucky Seven program, you should save it to disk. Visual Basic saves your form’s code and objects in one file and the "packing list" of project components in another file. (The project components are listed in the Project window.) You can use these component files individually in other programming projects by using the Add File command on the Project menu. To save a program in Visual Basic, click Save Project As on the File menu or click the Save Project button on the toolbar.
Save the Lucky Seven program
- On the File menu, click the Save Project As command.
You can save your program at any time during the programming process.
- Select the Less02 folder in the dialog box, if it’s not already selected.
- Type MyLucky in the File Name text box, and press Enter.
I recommend that you save each project you create in this book by using the My prefix to keep a record of your progress and to preserve the original practice files. That way you can check the original files if you have any problems.
- Type MyLucky and press Enter.
The complete Lucky program is located in the Vb6SbsLess02 folder.
Run the program
- Click the Start button on the toolbar.
Start button
- Click the Spin button.
>>
Because a seven appears in the first label box, the stack of coins appears and the computer beeps. (The sound depends on your Windows Control Panel setting.) You win!
- Click the Spin button 15 or 16 more times, watching the results of the spins in the number windows.
- When you’ve finished experimenting with your new creation, click the End button.
Your last task in this lesson is to complete the development process and create an application for Windows, or an executable file. Applications for Windows created with Visual Basic have the filename extension .exe and can be run on any system that contains Windows 95, Windows 98, or Windows NT 3.51 or later, and the necessary support files. (Visual Basic installs these support files—including the dynamic link libraries and ActiveX controls—automatically. If you plan to distribute your applications, see Microsoft Visual Basic 6.0 Programmer’s Guide by Microsoft Press for more information.)
An .exe file can run under any recent version of Microsoft Windows.
Create an executable file
- On the File menu, click the Make MyLucky.exe command. (Visual Basic adds your program’s name to the command automatically.)
tip
The Project Properties dialog box (accessed from the Project menu) contains a Compile tab that you can use to control advanced features related to your program’s compilation. These include optimizations for fast, efficient code; small, compact code; debugging; and other specialized operating conditions. By adding these sophisticated features to the compilation process, Visual Basic makes available to the professional developer tools that have traditionally been associated with the most efficient compilers, such as Microsoft Visual C++.
- Click OK to accept the default filename and location for the file.
To run this program later under Windows, use the Run command on the Start menu or double-click the filename in Windows Explorer. You can also create a shortcut icon for MyLucky on the Windows desktop by right- clicking the Windows desktop, pointing to New, and then clicking Shortcut. When you are prompted for the location of your application file, click Browse and select the MyLucky executable file in the Vb6SbsLess02 folder. Click the Open, Next, and Finish buttons, and Windows will place an icon on the desktop that you can double-click to run your program. The shortcut icon will look like this:
- On the File menu, click Exit to close Visual Basic and the MyLucky project.
- The Visual Basic Programming System closes.
Adding to a Program
You can restart Visual Basic at any time and work on a programming project you have stored on disk. You’ll restart Visual Basic now and add a special statement named Randomize to the Lucky Seven program.
Reload Lucky Seven
- Click the Start button on the Windows taskbar, point to Programs, point to Visual Basic 6.0 (or Visual Studio), and then click the Visual Basic 6.0 program icon.
- Click the Recent tab in the New Project dialog box.
- Double-click MyLucky to load the Lucky Seven program from disk.
Now you’ll add the Randomize statement to the Form_Load procedure, a special procedure that is associated with the form and that is executed each time the program is started.
- Double-click the form (not one of the objects) to display the Form_Load procedure.
- Press the Spacebar four times, type Randomize, and press the Down Arrow key.
- Run the new version of Lucky Seven, and then save the project to disk. If you plan to use the new version a lot, you may want to create a new .exe file too. Visual Basic does not update executable files automatically when you change the source code.
If you want to continue to the next lesson
- Keep Visual Basic running, and turn to Lesson 3.
If you want to exit Visual Basic for now
- On the File menu, click Exit.
To | Do this | Button |
Create a user interface | Use toolbox controls to place objects on your form, and then set the necessary properties. Resize the form and the objects as appropriate. | |
Move an object | Drag the object on the form by using the mouse. | |
Resize an object | Click the object, and then drag the selection handle attached to the part of the object you want to resize. | |
Delete an object | Click the object, and then press Del. | |
Open the Code window | Double-click an object on the form (or the form itself). or Click the View Code button in the Project window when a form or module name is highlighted in the Project window. | |
Write program code | Type Visual Basic program statements associated with the object you want to program in the Code window. | |
Save a program | On the File menu, click the Save Project As command. or Click the Save Project button on the toolbar. | |
Create an .exe file | On the File menu, click the Make filename.exe command. | |
Reload a project | On the File menu, click the Open Project command. or Double-click the file in the Recent tab of the New Project dialog box. |
Source http://www.visualbasicbooks.com
Reviews:
Post a Comment