GETTING COMFORTABLE MOVING AROUND THE VISUAL BASIC 2005 EXPRESS EDITION IDE


Visual Basic applications are created using Visual Basic's built-in IDE. The Visual Basic IDE provides tools such as a compiler, which translates application code into a finished executable program; a debugger, which assists in tracking down and fixing programs; and tools for managing projects.

The Visual Basic 2005 Express IDE features a standard menu, numerous toolbars, and a number of different windows. Because Microsoft has crammed so much into the IDE, there is no way that all of the available toolbars and windows can be displayed at the same time. Instead, Microsoft has come up with a number of clever ways of allowing these resources to share the same space.

Figure 2.5 shows how Visual Basic 2005 Express IDE looks the first time you use it to open up a new project.

image from book
Figure 2.5: The Visual Basic IDE only has room to show a portion of the available toolbars and windows at any one time.

As Figure 2.5 shows, the default layout of the Visual Basic IDE features a number of different elements. Each of the key elements shown in Figure 2.5 will be covered in detail later in this chapter.

One nice feature of the IDE is AutoDock. AutoDock allows you to move windows around in the IDE by using your mouse to reposition them. As you move them near the edge of the IDE, an outline appears, showing where the IDE will automatically redock the window if you let it go. This makes it easy for you to reorganize the placement of windows within the IDE to suit your own personal preferences.

Be careful when repositioning windows within the IDE. There are so many windows available that it is all too easy to misplace them or even accidentally rearrange them.

From time to time, you will either accidentally or deliberately close a window within the IDE. Don't panic if you later discover you need it back. Instead, click on the View menu and select the appropriate window to display it again. The IDE provides so many different windows that it cannot show them all directly under the View menu. If you don't see the window that you are looking for listed there, select the Other Windows option and look for it in the submenu that appears.

Because the IDE is so packed full of features, Microsoft has had to employ a few organizational tricks in order to make everything fit. In some cases, two or more windows may share the same space in the IDE. Each tab identifies its associated windows. You can jump between windows by selecting the appropriate tab.

Another useful feature that you'll see a lot in the IDE is the presence of a thumbtack at the top of windows such as the Solution Explorer and Properties windows. The thumbtack represents an autohide feature that allows you to shrink down a window to a tab that is connected to the edge of the IDE where the window is docked. This way you free up space in the IDE for other windows without having to close any windows, and you can later restore a docked window by clicking on its tab. For example, take a look at Figure 2.6. Here you will see that the Solution Explorer window has been docked as a tab on the right side of the IDE in order to provide additional room for the Properties window.

image from book
Figure 2.6: Microsoft has implemented a number of clever organizational tricks to make the IDE more manageable.

Trick 

The IDE is highly customizable. Click on the Tools menu and then select the Customize option to configure which of the IDE's many toolbars are displayed. In addition, you can customize any number of IDE features, such as how the form designer looks and how the code editor behaves, by clicking on the Tools menu and selecting Options.

Navigating the IDE Menu

The Visual Basic 2005 Express IDE includes a comprehensive menu, which lists and organizes the various commands and options available to you as you work. Visual Basic's IDE is a dynamic tool. It automatically changes based on the particular task that is before it.

The following list identifies the IDE menus and summarizes the functionality that they provide:

  • File. Menu options for opening and saving projects and solutions

  • Edit. Text-editing options such as Undo, Copy, Cut, and Paste

  • View. Switch between the form designer and code editor and access other windows such as the Toolbox, Solution Explorer, and Properties windows

  • Project. Add new forms, controls, and components to a project

  • Build. Build or compile a standalone version of your application

  • Debug. Test the execution of an application or step through a program that has been stopped with an error or a breakpoint

  • Data. Configure connections to data sources such as a local database

  • Tools. Collection of different options, including the Options submenu where you can customize the IDE and various project settings

  • Windows. Select and arrange open windows

  • Community. Access to on-line Visual Basic resources

  • Help. Access to Visual Basic's integrated help system, including access to both local and online help topics

Working with Toolbars

As is the case with any Windows-based application, Visual Basic 2005 Express makes it easy to access certain commands using toolbars. By default, Visual Basic automatically displays its Standard toolbar, shown in Figure 2.7. The items displayed by toolbars may also change dynamically based on what you happen to be doing at the time.

image from book
Figure 2.7: Standard toolbar provides access to commonly used IDE commands and windows.

The Visual Basic 2005 Express IDE includes more than a dozen toolbars, each of which provides single-click access to various commands. For some of the toolbars, you can configure whether or not they are displayed by clicking on the View menu and then selecting the Toolbars option. Optionally, you can configure the display of all the available toolbars by clicking on the Tools menu and selecting Customize.

Trick 

You can also configure the display of toolbars by right-clicking on any visible toolbar and selecting the desired toolbar from the list that will appear.

Each icon on a toolbar performs a specific command or task. Visual Basic 2005 Express has too many toolbars to go over each of their icons in this book. You can find out about the specific function for each toolbar icon by placing your cursor over it, which results in its name being displayed as a ToolTip. However, you can get a pretty good feel for the purpose behind each toolbar based on its name.

Form Designer Basics

The form designer, shown in Figure 2.8, provides you with the ability to visually create GUIs (graphical user interfaces) using drag and drop. The form designer makes Visual Basic visual. The form designer shares space within the IDE with the Getting Started window and the code editor window, which is what you'll use to enter your Visual Basic programming statements.

image from book
Figure 2.8: Visual Basic automatically creates a new form containing basic Windows elements each time you open up a new Visual Basic project.

Trick 

Sometimes when you are working with the form designer you may notice that there is an asterisk in the tab for the window just to the right of the form name. This asterisk indicates that you have made changes to the form that you have not saved yet. It is always a good idea to frequently save changes any time you modify your Visual Basic applications.

As you have already learned, you create an application window using a form. An application can have more than one form. As you saw when you created the Joke Machine application in Chapter 1, "An Introduction to Visual Basic 2005 Express," an application window is created by adding controls to it. These controls are copied over from the Toolbox. Once added to your form, you can customize controls by changing their size or editing their associated properties. Once you have a prototype of your form set up to look like you want it to, you'll need to add code to the controls to make them behave and work like you want them to.

The form designer makes relocating and aligning controls easy. It provides visual indicators that show the location of each control relative to the location of other controls on the form, as demonstrated in Figure 2.9.

image from book
Figure 2.9: The form designer provides visual indicators that assist you in aligning form controls.

Trick 

You can also use commands located on the Format menu to automatically align controls on a form. For example, if you had three buttons of varying sizes on a form and wanted them all to be the same size, you could select them all by holding down the Ctrl key as you click on each button, and then click on Format, Make Same Size, and the Height and width commands.

Trick 

If you find that you are continually accidentally moving controls while working on a Windows interface, you can lock controls into place so that they cannot be moved by mistake. To do this, click on the Format menu and click on the Lock Controls command. If later you want to move a control, click on Lock Controls command again.

Understanding the Code Editor

The code editor facilitates the storage and viewing of the programming code that drives your Visual Basic applications. The easiest way to access it is to double-click on a form or one of the controls on the form. This automatically switches you from the form designer view to the code editor view as shown in Figure 2.10. Best of all, it also automatically places your cursor at the right location to begin entering code for the resource that you double-clicked on.

image from book
Figure 2.10: The code editor is the tool that you use to create and modify program code for your Visual Basic applications.

Trick 

You can configure a number of features that affect the way the code editor looks and acts by clicking on the Tools menu and selecting Options. When the Options window appears, select the Text Editor option located on the left-hand side of the Options window and change any of the configuration settings that will be displayed on the right-hand side of the dialog.

Program code associated with a form and any of the controls placed on that form is stored alongside the form. Therefore, if a Visual Basic application contains more than one form, the code associated with each form is stored and displayed separately.

Trick 

In addition to storing program code alongside a form, you can store the code in a separate module, which you can then use to refer back to a form and its controls.

At the top of the code editor are two drop-down lists. The first drop-down list is the Class Name list, from which you can select any of the controls located on the form. The second drop-down list is the Method Name list, which provides access to any event associated with the currently selected object. By using these two drop-down lists together, you can locate any code procedure. If you use these controls to look for a procedure that has not been created yet, the code editor will define a new procedure for that control and event on your behalf.

Visual Basic Assisted Code Development

One of the really nice things about Visual Basic is that it does so much work for you under the covers. For example, you don't have to figure out how to create a button or a text box. Visual Basic already makes them available to you as controls located in the Toolbox. Just as Visual Basic greatly simplifies form design, it helps streamline the code development process. For example, as you saw in Chapter 1 when you created the Joke Machine, Visual Basic automatically generates a lot of code for you. For example, create a new project and place a Label, a Textbox, and a Button on the form. Then double-click on the form and you'll see that Visual Basic automatically generates the following code for you.

 Public Class Form1     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load     End Sub End Class 

Trick 

Actually, the format of the code statements that you will see when performing the above steps will vary slightly from the statements presented here. In order to make things fit onto the pages of this book, I will have to split some programming statements up into multiple pieces, using the continuation character (_).

As you can see, Visual Basic has already framed out the overall organization of the program statements that will make up the application. Now, using the Class Name and Method Name drop-down lists, select Button1 control and the Click event. As soon as you do this, the code editor defines a new procedure for you, as shown below.

 Public Class Form1     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load     End Sub     Private Sub Button1_Click(ByVal sender As Object, _       ByVal e As System.EventArgs) Handles Button1.Click     End Sub End Class 

Now all that you have to do is type in the Visual Basic code statements that you want to be executed as part of these procedures, as was demonstrated in the Joke Machine project. I'll talk more about the benefits and use of procedures later in Chapter 8, "Enhancing Code Structure and Organization."

Color Coding, Automatic Indentation, and Spacing

You may have noticed back in Chapter 1 when you were creating the Joke Machine that the Visual Basic code editor did a number of things that made it easier for you to key in your Visual Basic code statements. For example, certain Visual Basic keywords were color coded in order to make them stand out. You will really learn to appreciate this feature as your applications grow in complexity and you end up writing more and more code. Color coding helps to make your code easier to read and work with by providing visual indicators that make your program code intuitively easier to follow along.

Another nice feature that you may not even have noticed is the automatic indentation of code statements, as demonstrated in Figure 2.11. By indenting groups of related code statements, your code is visually organized into logical chunks and becomes easier to read and understand.

image from book
Figure 2.11: The Visual Basic code editor automatically color codes statements and indents them to make them easier to read.

Another really handy feature of the code editor is automatic spacing. For example, you might try to enter the following code statement, exactly as shown below.

 TextBox1.Text="Hello" 

As soon as you press the Enter key, the code editor changes the statement to look like the line of code shown below.

 TextBox1.Text = "Hello" 

The changes to the line of code are subtle, but very important. If you look closely, you'll notice that a blank space has been added just before and after the equals sign to make the code easier to read. This is just another way that the Visual Basic code editor works to help make your coding experience as easy as possible, allowing you to focus on the task at hand without having to worry about little organizational details.

IntelliSense

A really nice feature that is directly integrated into the code editor is IntelliSense. IntelliSense was first introduced with Visual Basic 5.0. IntelliSense can be so helpful that many times you'll be able to get what you need from it without having to turn to other resources for help.

IntelliSense is responsible for displaying the pop-up boxes that you may have noticed when you were creating the Joke Machine back in Chapter 1. With IntelliSense, the Visual Basic IDE keeps an eye on your program statements as you type them and displays windows showing all the possible options available to you as you enter your code.

To better understand IntelliSense, let's look at a couple of examples. In the first example, shown in Figure 2.12, I created a form that contained a button and a text box. I then double-clicked on the button to open the code designer. I entered the word TextBox1 followed immediately by a period. In response, IntelliSense kicked in and displayed a pop-up window showing all the possible coding options available to me. In this example, I clicked on Text, which represents the TextBox control's Text property, and IntelliSense automatically appended the word to my code. All that remained for me to do was to finish writing the rest of the code statement as shown below.

image from book
Figure 2.12: IntelliSense provides dynamic assistance as you enter your code statements.

 TextBox1.Text = "Click on Me!" 

IntelliSense can help in the formation of more complex programming statements as well. For example, with the next code statement, my intention was to gray out and prevent the user from being able to click on the Button1 button. I started the statement by keying in the name of the Button1 control followed by a period. IntelliSense then kicked in, as shown in Figure 2.13, and displayed a pop-up window showing me all of my available options. I clicked on Enable and IntelliSense then appended that word to the code.

image from book
Figure 2.13: IntelliSense can assist you in the creation of complex code statements and in reducing typo mistakes.

Next I typed a space and pressed on the equals (=) key. Once again, IntelliSense jumped into action, displaying a pop-up window showing the two options that were available to me. (Also, just to the right of the pop-up dialog, a ToolTip was displayed, explaining what the Enabled method does.) I selected False and IntelliSense completed the code statement by appending the word False to the end of it.

Trick 

Another nice IntelliSense feature is the ability to use the Ctrl and Space keys together to tell the code editor to start it up. For example, suppose you created a form with a large number of controls and were having trouble remembering the name of a particular control for which you wanted to write some code. In this scenario, you could type the first letter or two of what you thought the control might be named and then could press and hold down the Ctrl key while also pressing the Space key. When you do this, IntelliSense starts and displays the names of all available resources that begin with those letters, as demonstrated in Figure 2.14.

image from book
Figure 2.14: Using the Ctrl and Space keys to manually start up IntelliSense.

What's in the Toolbox?

The Toolbox window, shown in Figure 2.15, contains all of the controls that are available to your Visual Basic applications. By dragging and dropping an icon from the Toolbox onto a Visual Basic form, you automatically add its functionality to your application. For example, in this book you will learn how to work with controls such as Label, Button, and TextBox.

image from book
Figure 2.15: The Toolbox window provides access to the controls with which you create windows.

The Label control allows you to place a string of text anywhere on a form. The Button control allows you to add as many buttons to your form as you need. You can then customize the appearance of each button and add code to it in order to make your application perform a specific task whenever the user clicks on it. The TextBox field provides the ability to collect text input directly from users. These are just a few of the dozens of controls that are available to you.

By default, the Toolbox window displays a list of controls with their names just to the right of each control. Toolbox controls are organized into the following groups:

  • All Windows Forms. A list of all available controls.

  • Common Controls. Commonly used interface controls.

  • Containers. Controls that can be used to organize other controls.

  • Menus & Toolbars. Controls that facilitate the creation of menus and toolbars.

  • Data. Controls that facilitate the establishment of a connection to a local database.

  • Components. Controls that facilitate the collection of information regarding how the computer is operating.

  • Printing. Controls that provide access to print features.

  • Dialogs. Controls that provide access to various dialog windows.

  • General. Contains controls that do not fit in the above categories.

Trick 

Because there are so many available controls in the Toolbox, you have to scroll down to view them all. Once you learn to identify each control by its graphic icon, you can modify the Toolbox window so that it only displays a list of icons. This enables you to view the available controls at one time with no scrolling. To set this up, right-click on the Toolbox window and select the List View option from the drop-down menu that appears. Also, if you forget what a given control icon represents, just place you cursor over it and its name is displayed as a ToolTip.

There isn't enough space in this book to cover every Visual Basic 2005 Express feature, such as all of the Toolbox controls. However, rest assured that as you work your way through this book, you'll learn how to work with a lot of other controls.

Trick 

Visual Basic provides access to more controls than are displayed by default in the Toolbox. You can view these additional controls and add them to the Toolbox as necessary by right-clicking on the Toolbox and selecting Choose Items. This opens the Choose Toolbox Items dialog where you will find additional controls listed on either of two tabs. The first tab is .NET Framework Components. It stores controls that are designed to work with the .NET Framework. The second tab is listed as COM Components. The controls listed here are legacy controls for which .NET equivalent controls have yet to be developed. To add a control, select it and click on OK.

Working with Solution Explorer

Solution Explorer displays the projects and files that make up your Visual Basic applications. Solution Explorer organizes its contents in a hierarchical format, starting with the solution, followed by its member's projects, and then all the files that make up those projects, as demonstrated in Figure 2.16.

image from book
Figure 2.16: Using Solution Explorer, you can manage the projects and files that make up your Visual Basic applications.

You can also use the Solution Explorer to locate and open a file by double-clicking on it. If you select a file that is associated with both the form designer and code editor, you can select which tool you wish to work with by clicking on the appropriate icon as shown in Figure 2.16.

Understanding How to Use the Properties Window

Properties are a key component in the development of any Visual Basic application. By specifying the values assigned to a form using the Properties window, you are able to specify its initial appearance and behavior. Later, in your program code, you can modify the value of many properties and dynamically change them as your application executes.

Every control that you can place on a form when creating your application's graphical interface also has its own collection of properties. By setting property values associated with a control, you can specify control text, size, color, location, and behavior.

You have already seen how to work with control properties back in Chapter 1 when you created the Joke Machine. All you have to do is select a control and its associated properties are automatically displayed in the Properties window, as demonstrated in Figure 2.17.

image from book
Figure 2.17: Examining the properties associated with a Button control.

As you can see, the name of each property is shown in the left-hand column of the window, and any values assigned to those properties are shown in the right-hand column.

By default, the Visual Basic IDE organizes the display of properties by category. This assists you in finding the right properties to modify when you are not sure what the name of the property you are looking for is but you have a good guess as to what category it belongs to. However, as you become more comfortable with Visual Basic programming, you may find that you prefer to have control properties listed alphabetically, so that you can quickly scroll down and locate the one that you know you are looking for. You can switch between category and sort view by clicking on either the Categorized or Alphabetical icons located at the top of the Properties window, as shown in Figure 2.17.

For most controls, all that you have to do to modify one of their associated properties is to type a new value for it in the Properties window. However, some properties have a finite number of available values. When this is the case, an iconic arrow is displayed when you select the properties. For example, as demonstrated in Figure 2.18, only two possible values are available for the Button control's Enabled property (True or False).

image from book
Figure 2.18: When only a finite number of values are available for a property, the Properties window displays them in a drop-down list for your selection.

For some properties, such as the Font property, you'll notice that when you select them, three ellipses are displayed in the value field. When you click on the ellipses, a dialog appears, from which you can select the appropriate value. For example, Figure 2.19 shows the dialog that appears when you want to modify the values associated with the Font property.

image from book
Figure 2.19: Sometimes you will be presented with an additional dialog from which you can select the values that you want to assign to a given property.

Trick 

You can edit most, but not all, of the properties belonging to a given object at design time, which is when you are developing your application using the IDE. However, some properties are only available at run-time, which is not until your application has been finished, saved, and then executed. For example, the font type and size associated with a control is always available at design time, whereas the text entry for a control that holds user input, such as a TextBox control, won't be available until your application is running. You cannot, therefore, set properties only available at run-time from within the Properties window at design time.

The Component Tray

Most of the controls on the Toolbox work by copying an instance of the control onto a Visual Basic form. Once added to a form, you can modify the control and access its properties. However, some controls don't actually appear on your forms when you add them because they don't take a visual form that users can see and interact with. Perhaps the best example of this type of control is the Timer control.

A Timer control provides the ability to trigger activity at certain time intervals. For example, the Click Race game that you will learn how to create later in this chapter uses a Timer control to limit the amount of time that the player has to play the game. So if the Timer control does not appear on a form, how can you see that you have successfully added it to your application, and how do you access its properties at development time? The answer is by using a component tray located at the bottom of the form designer.

Any time that you add a control that cannot appear on a form, Visual Basic automatically displays it in a component tray, as demonstrated in Figure 2.20.

image from book
Figure 2.20: Because the user cannot see or Interact with the Timer object, it is added to a component tray.

As you can see in Figure 2.20, the Timer control has been added to the form. You can now select it and set its Properties just like any other control that you can add to a Visual Basic form.

Other Windows

There are a number of other IDE windows available to you as you develop your Visual Basic applications. Some are very specialized, and you will only need to work with them at certain times. For example, the Error List window automatically appears if you attempt to run a program with an error in it within the IDE. Table 2.1 lists these other windows, which are discussed, where relevant, in later chapters.

Table 2.1: Additional IDE Windows

Windows

Description

Object Browser

Provides the ability to view objects and their members

Error List

Displays information about errors that occur when testing your applications

Immediate

Provides the ability to issue commands and test expressions while testing your applications

Task List

Displays tasks that Visual Basic identifies as needing to be done

Back to the Click Race Game

In the Click Race game, the player is required to click on two buttons as many times as possible in order to score points in a 30-second period. However, in order to rack up points, the player must click on one button and then the other button before returning to click on the first button. Therefore, the game requires that the player be not only quick with the mouse button, but also quick and precise in moving the mouse around.

Designing the Game

The Click Race game is played on a single window. It is made up of a form and six controls shown in Table 2.2.

Table 2.2: Form Controls for the Click Race Game

Control

Description

TextBox1

Displays the number of valid mouse clicks

Label1

Descriptive label for the text box

Button1

One of two game buttons

Button2

One of two game buttons

Button3

Button used to start game play

Button4

Button used to close the game

Timer1

Timer control used to control the length of a game

Step 1: Creating a New Visual Basic Project

The first step in creating the Click Race game is to start Visual Basic and open a new project.

  1. If you have not already done so, start up Visual Basic 2005 Express and then click on File and select New Project. The New Project dialog will appear.

  2. The Click Race game runs as a graphical Windows desktop application, so select Windows Application.

  3. Next, type Click Race as the name of your new application in the Name field located at the bottom of the New Project window.

  4. Click on OK to close the New Project dialog.

Visual Basic will now create a new project, including an initial form, in its IDE.

Step 2: Creating the User Interface

Now it is time to add the controls required to assemble the game's interface. The overall layout of the game's interface is shown in Figure 2.21.

image from book
Figure 2.21: Completing the interface design for the Click Race game.

  1. Let's begin by adding a TextBox to the form. By default, Visual Basic assigns the name Textbox1 to the control.

  2. Then let's add a Label, which Visual Basic automatically names Label1, to the form.

  3. Move and resize TextBox1 and Label1 to the approximate location shown in Figure 2.21.

  4. Add the first button to the form and place it in the lower left-hand corner. Visual Basic assigns it the name Button1.

  5. Add the second button to the lower right-hand corner. Visual Basic assigns it the name Button2.

    Trap 

    It is important that you not get the buttons mixed up. You will need to know which button is which when it is time to begin adding code to the application.

  6. Then add the third button to the upper right-hand corner of the form. Visual Basic assigns it the name Button3.

  7. Next, add a fourth button just beneath it. Visual Basic assigns it the name Button4.

  8. Finally, add a Timer control to your form, which Visual Basic names Timer1. The Timer1 control will actually be displayed on a Component Tray.

The layout and design of your Visual Basic form is now complete and should look like the example shown in Figure 2.21, except that the Timer1 control is displayed in a Component Tray just below the form.

Step 3: Customizing Form and Control Properties

Before you start customizing the properties associated with the controls that you just added to the form, let's change one of the properties belonging to the form itself. Specifically, let's modify the form so that it displays the text string of Click Race Game in its title bar. To do this, click anywhere on the form, except on top of one of its controls, and then locate the Text property in the Properties windows and replace the default value of Form1 with Click Race Game.

The first control to modify is the Textbox1 control. Table 2.3 lists all of the properties that you should modify and shows what their new values should be.

Table 2.3: Property Changes for the Textbox1 Control

Property

Value

BackColor

Info

ForeColor

HotTrack (on the System Tab)

ReadOnly

True

Font

Arial

Font

Regular

Font

Size 14

Size

132, 29

Once you have completed making the property changes for the TextBox1 control, let's work on the Label1 control by making the property changes shown in Table 2.4.

Table 2.4: Property Changes for the Label1 Control

Property

Value

Font

Arial

Font

Bold

Font

Size 12

Text

Number of Clicks

Now, referring to Table 2.5, modify the properties associated with Button1, Button2, Button3, and Button4.

Table 2.5: Property Changes for the Button1 Through Button4 Controls

Button Name

Property

Value

Button1

Text

Click Me!

Font

Arial

Font

Regular

Font

Size 9

Button2

Text

Click Me!

Font

Arial

Font

Regular

Font

Size 9

Button3

Text

Start Game

Font

Arial

Font

Regular

Font

Size 9

Button4

Text

Exit

Font

Arial

Font

Regular

Font

Size 9

There are two additional property modifications that need to be made. They are to the Timer1 control located in the Component Tray. By default, the Timer1 control's Interval property is set to 100 by Visual Basic at design time. Interval represents the amount of time in milliseconds that passes during each interval measured by the timer control. It is a lot easier for people to think in terms of seconds than in terms of milliseconds. So let's change the value assigned to Interval1 to 1000 as shown in Table 2.6.

Table 2.6: Property Changes for the Timer1 Control

Property

Value

Interval

1000

Enabled

True

Lastly set the Timer control's Enabled property equal to true. Otherwise it will not execute when the application is executed.

That's all the property modifications that are required for the Click Race game. Now it is time to give life to the application by adding the programming code that will make the game run.

Step 4: Adding a Little Programming Logic

OK, it is time to start coding. If you double-click on Form1, Visual Basic starts things off for you by adding a number of lines of code, as shown below. Actually, what you'll see in the code editor window is slightly different than what you see here. Take a look at the end of the second line of code shown below. Notice that it ends with the underscore character. In Visual Basic the underscore character is used as a continuation character. I added it where I did so that I could make the code statement a little easier to read by breaking it out into two lines. Other than this cosmetic change, everything else is exactly the same.

 Public Class Form1     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load     End Sub End Class 

Visual Basic 2005 Express is an OOP (object-oriented programming) language. In order to work with an object, you must define an instance of the object in your application. In the case of the above code, in the first statement, Visual Basic defines an object named Form1 on your behalf, which extracts everything its needs from the Visual Basic Class Library. All code for the Form1 object or any of the controls that you have added to the form is placed somewhere after the Public Class Form1 statement and before the closing End Class statement. These two statements define the beginning and end of the code affecting the Form1 object.

Trick 

In between the Public Class Form1 statement and the End Class statement are two more statements. These statements identify the beginning and end of the Form1 Load event procedure. Take a look at the first of these two statements and you will see that the first statement assigns the procedure the name Form1_Load. You can change the name of the procedure to anything that makes sense to you.

The Load keyword refers to the form's Load event. Events occur in Visual Basic whenever something happens. For example, when a form first appears or loads, the Load event for that form executes. Therefore, this procedure executes when the application starts (for example, when the form first loads). Don't worry if this explanation is a little difficult to grasp just yet. I shared it with you now just to try and give you a feel for what Visual Basic is doing. I'll go over procedures and events in much more detail in later chapters.

Now it is time to begin adding code to the Click Race game. Again, since you won't start learning how to formulate Visual Basic statements until Chapter 4, "Working with Menus and Toolbars," just follow along and make sure that you enter any Visual Basic statements exactly as I'll show you.

For starters, add the two statements shown below in bold exactly where shown. These statements define two variables that the application will use to keep track of how many times the player has clicked on the game's buttons and how long the game has been running.

 Public Class Form1     Dim intCounter As Integer = 0     Dim intTimerCount As Integer = 0     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load     End Sub End Class 

Next, add the two statements shown below in bold in the Form1_Load procedure. These statements execute as soon as the form loads and gray out the two buttons used to play the game.

 Public Class Form1     Dim intCounter As Integer = 0     Dim intTimerCount As Integer = 0     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load         Button1.Enabled = False         Button2.Enabled = False     End Sub End Class 

Now click on the Form1.vb [Design] tab to return to the designer view and then double-click on Button1. This switches you right back to the code editor, where you will see that Visual Basic has added a new procedure named Button1_Click. Add the four statements shown below in bold to this procedure exactly as shown. The first statement adds a value of 1 to the intCounter variable, which the game uses to track the total number of mouse clicks made by the player. The second statement displays the value of the value of intCounter in the Textbox1 control so that the player will know that a click has been counted. The next two statements gray out or disable Button1 and enable Button2 (because the game forces the player to alternate the clicking of these two buttons).

 Private Sub Button1_Click(ByVal sender As System.Object, _   ByVal e As System.EventArgs) Handles Button1.Click     intCounter = intCounter + 1     TextBox1.Text = intCounter     Button1.Enabled = False     Button2.Enabled = True End Sub 

Now click on the Form1.vb [Design] tab to return to the designer view and then double-click on Button2. This switches you back to the code editor. You'll notice that Visual Basic has added a new procedure named Button2_Click. Add the four statements shown below in bold to this procedure. As you can see, these statements look almost exactly like the four statements that you added to the previous procedure, except that the last two statements switch the enabling and disabling of the two game buttons.

  Private Sub Button2_Click(ByVal sender As System.Object, _   ByVal e As System.EventArgs) Handles Button2.Click     intCounter = intCounter + 1     TextBox1.Text = intCounter     Button1.Enabled = True     Button2.Enabled = False End Sub 

Now it is time to add some code to the game's Start button (Button3). Start by clicking on the Form1.vb [Design] tab to return to the designer view and then double-click on Button3. This switches you back to the code editor. You'll notice that Visual Basic has added a new procedure named Button3_Click. Add the six statements exactly as shown below to this procedure. This procedure is used to start or restart the game at anytime. The first two statements reset the values assigned to the game's two variables back to zero. The next statement clears out Textbox1. Two statements that follow enable Button1 and disable Button2. The last statement restarts the Timer1 control.

 Private Sub Button3_Click(ByVal sender As System.Object, _   ByVal e As System.EventArgs) Handles Button3.Click     intCounter = 0     intTimerCount = 0     TextBox1.Text = ""     Button1.Enabled = True     Button2.Enabled = False     Timer1.Enabled = True End Sub 

Now let's fix up the Exit button (Button4) so that it will close the Click Race game when the player clicks on it. Click on the Form1.vb [Design] tab to return to the designer view and then double-click on Button3. This switches you back to the code editor, where you'll see that Visual Basic has added a new procedure named Button4_Click. Add the following statement to it, shown in bold, exactly as shown below. This statement tells Visual Basic to exit the application.

 Private Sub Button4_Click(ByVal sender As System.Object, _   ByVal e As System.EventArgs) Handles Button4.Click     Application.Exit End Sub 

Now all that is left to do is to add some code to the Timer1 control so that it will limit the player's turn to 30 seconds. Click on the Form1.vb [Design] tab to return to the designer view. Double-click on Timer1. Visual Basic automatically adds the Timer1_Tick procedure to your application. Add the five Visual Basic statements shown below in bold to this procedure. The first statement tells the Timer1 control to keep track of the number of seconds that it has run. Remember that you previously configured the Timer1 object's interval property so that the Timer1 control would execute every second. The next four statements will execute as soon as the Timer1 control has run for 30 seconds, at which time the two game buttons will be disabled, thus ending the player's turn.

 Private Sub Timer1_Tick(ByVal sender As System.Object, _   ByVal e As System.EventArgs) Handles Timer1.Tick     intTimerCount = intTimerCount + 1     If intTimerCount = 30 Then       Button1.Enabled = False       Button2.Enabled = False     End If End Sub 

Step 5: Testing the Execution of the Click Race Game

OK. That's it. The Click Race game should be ready to go. Try running it by pressing the F5 key. If any errors occur, go back and double-check the code statements that you added to make sure that you did not make any typos.




Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
ISBN: 1592008143
EAN: 2147483647
Year: 2006
Pages: 126

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net