Beginning Visual Basic - Project 1a

Procedural (Linear) verses Event-Driven Programming—Hello World

What is Procedural (Linear) Programming

All computer programming of the past was Linear. A program was composed of lines of code that were executed one line after another from top to bottom (lines of code which achieved a specific goal were usually grouped together into what are called Procedures. Never-the-less, these procedures were executed in a Linear way). When the program was run, it executed its code without delay. This type of programming is called Procedural or Linear Programming. Programming in Visual Basic adds a twist to what is historically known as procedural programming with the introduction of Event-Driven Programming.

What is Event-Driven Programming

When you run a Windows program, here’s what you see: A window with Objects (Controls) inside it, such as Command buttons, Text boxes, List Boxes, Options buttons, etc. And what does it do? Nothing—It waits for an event. An event is an action, usually (but not always) initiated by the user, such as clicking on a command button, moving the mouse pointer, pressing a key on the keyboard, etc. After an event occurs, any code inside the appropriate event procedure of the object which received the event is executed. Most objects have Event procedures attached to them, (e.g., Command Buttons come with a Click event-procedure).

Hello World

In a bow to tradition, you will now create a Hello World program. Ever since I can remember, the first program that all beginning programmers write is a Hello World program. What a Hello World program entails is this: You create a simple program that writes the message "Hello, world!" on the screen. Sound simple? It is. As a Procedural application using the old version of Basic for DOS, this program can be as small a one line of code, like so:

Print "Hello, world!"

When the old, linear Basic version of this program is run, the above line of code is executed immediately, the message "Hello, world!" is displayed on the screen, and the program terminates. This same line of code can be used in your Event-driven Visual Basic version of this program as well. But where does this code go? Remember that in an Event-driven programming environment, almost all code must be placed within the event procedures of the controls used in the program. Since the first version of this program will have only one control—a blank Form—you must decide which event procedure of the Form to insert the Print "Hello, world!" command in.

Below is a list of just a few of the Event Procedures that come with a Form. One of these must contain the Print "Hello, world!" code for your program. But which one?

Event procedure name

Event which executes it

Form_Activate The Form becomes the active window
Form_Click The user clicks the mouse on the form
Form_MouseMove The user moves the mouse pointer over the form
Form_Resize The user changes the size of the form
Form_DblClick The user double-clicks the mouse on the form

To duplicate the action of the old-time Linear version of this program, you could put the Print "Hello, world!" command into the Form_Activate event procedure. This would execute the print command, when the program is first run (or activated). But that doesn’t really show how the Event-Driven programming of Visual Basic works. Let’s experiment, and see how the Print "Hello, world!" command can be inserted into any of the above event procedures, and still do the job. Follow these steps to see how:

1. Run Visual Basic (this starts a new Project automatically. If you’re already in Visual Basic and want to manually start a new Project, just select New Project under the File menu, and choose Standard EXE as the project type).

a) Press the F7 key, or click the View Code button at the top of the Project Explorer window to pop open the Code Window.

b) Select Form on the Object drop-down menu of the code window (the drop-down list on the top Left of the code window).

c) Pull down the Procedure drop-down menu and scroll it up and down to see all of the event procedures that come with a Form (the drop-down list on the top Right of the code window). Choose the Activate event procedure from the list.

The code for the Form_Activate event procedure should look like this. Blank, except for the procedure’s beginning and ending statements:

Private Sub Form_Activate()

End Sub

Your cursor (the vertical flashing line) should be sitting on the blank line between these two lines. Press the Tab key once to indent the blank line and type this command:

Print "Hello, world!"

Now click the Start button on the toolbar to run the program. What happens? Time to experiment: Remove the Print "Hello, world!" command from the Form_Activate event procedure, and put it in the Form’s Click event procedure (Form_Click). Select the Click event procedure from the drop-down Procedures list at the top right of the Code Window like you selected the Activate event procedure earlier.  Run the program again, now click anywhere on the form. What happens? Click on the Form again. What happens? Try running the program after putting the Print "Hello, world!" command into each of the different event procedures listed above, and see what happens (Important Note: Be sure to delete the Print "Hello, world!" code from each Event procedure before trying it in another one, so that the code is only inserted into one event procedure at a time).
 

Beginning Visual Basic - Project 1

Command Buttons — A taste of Object Oriented Programming

Good Programming Practice

Before beginning any Visual Basic programming project, pull down the Tools menu and choose Options. Click on the Editor Tab. Find the Require Variable Declaration option in the Code Settings group and make sure it is turned on. Then click the OK button. It is good programming practice to always declare variables you use in your programs. By turning the Require Variable Declaration option on, Visual Basic will remind you to dimension any variables you try to use without dimensioning them first.

Declare all variables by Dimensioning them with the Dim command prior to use.

The First Project

When you start a new project in Visual Basic you begin with a blank form (which will be the main window of your program). To the left of the blank form is the Object Toolbox (hereafter also called the Control Toolbox). From this toolbox you can choose objects (hereafter also called Controls) that you want to include on your form.

For the first Visual Basic project, you will create a program that displays a sizable window with a single button displayed exactly in the center of it. The button’s caption will read, On. When the user clicks on the button, its caption will change to Off.

Run Visual Basic (this starts a new Project automatically. If you’re already in Visual Basic and want to manually start a new Project, just select New Project under the File menu, and choose Standard EXE as the project type). You begin with a blank Form. If the Properties window is not showing, press the F4 key to make it appear. Since this blank form contains no other Controls, the properties of the Form itself are displayed in the Properties window.

Note: Spaces are allowed in a Caption, but do not put spaces in the Names of forms, controls, or variables. Be "case conscious" while naming forms, controls, and variables in Visual Basic. While Visual Basic ignores the case of the letters used in names, you should not. Other programming languages such as C, and C++ are case sensitive languages. By practicing case sensitivity now, your transition to programming in C or C++ at a later date (If you so desire), will be greatly simplified.

The project itself also has Properties that weÆre going to set. Access this projectÆs properties by clicking on the Project menu at the top of the screen, then select Project1 Properties. Click on the General Tab of the Project Properties dialog box if it's not already selected.

In the Startup Object combobox make sure frmProj1 is selected (it should be by default). In the Project Name textbox type Project1. In the Project Description textbox type the following: Changes a command button's caption from "on" to "off". Leave all other settings at their defaults and click the OK button. It is important to set these options when you begin each project.

Pull down the File menu and choose Save Project. Since you haven’t previously given this project, or the project’s form file, names, you will be asked to do so. By default the name of your form file will be the same name you gave it in its properties: frmProj1 (with a .frm extension). Click the Save button to use this name. The project name will default to project1.vbp. Use this name also. As you can see, this project is comprised of 2 files (other projects will have more). The 2 files in this project include:

A Form file with an FRM extension. This file contains the Form, Control, and Code data that is the core of your program.

A Project file with a VBP extension. This file is a small text file that contains the names of the forms (with paths to their locations) that comprise the project, and other information about the initial appearance of the project when Visual Basic opens it.

Make sure your blank Form is visible by clicking on the View Object button of the Project Explorer window or by pressing Shift-F7. Now you are going to add a Command Button to your blank Form. (To find out what the different Control Toolbox buttons do, hold your mouse pointer over a button and a descriptive Tool Tip pops open to show you the name of that tool). Double click on the Command Button control on the Control Toolbox. You will see a command button with the default caption Command1 appear in the center of the blank form.

Make sure the button control you just added to your form is selected by clicking once on it (you’ll see sizer handles (black or dark blue dots) appear on each corner and on each side of the button when it’s selected).

Press the F4 key to pop up the button’s properties window.

  • Change the Caption property to the word On
  • Change the Name property of the Command Button to cmdToggle

Now you need to add some Code to the Click event procedure of the cmdToggle button.

Press the F7 key or double click on the new cmdToggle button. This pops open the Code Window for the Click procedure that’s built into all command button controls.

Notice the drop-down listbox in the upper left corner of the Code Window is the list of Objects on the Form. All the Controls used in the form are listed there, including the Form that the controls reside on (The form is also called the container of the controls).

Also notice the drop down listbox in the upper right corner of the Code Window which lists all the Event Procedures that go with each Control (Object). Here the different Event Procedures for the Control displayed in the Object list box are listed in alphabetic order. Those procedures which you have added code to appear in bold text.

Private Sub cmdToggle_Click() should be the first line that’s displayed at the top of the Code Window. cmdToggle_Click() is the name of this procedure. Notice how the name of our new command button control cmdToggle is connected by an underscore to the front of the procedure name Click(). That is how all procedures for controls appear. Sub does not stand for subroutine. Sub stands for a procedure which is below an object (as in a hierarchy). The Private designator indicates that this Sub procedure is accessible only to other procedures in the module (form) where it is exists.

End Sub designates the end of the procedure.

Adding Code to the Click procedure of your cmdToggle button.

When a user clicks on the cmdToggle button they trigger a Click Event, and any code in the cmdToggle_Click() event procedure is executed automatically. To change the caption of the button from On to Off, enter the following line of code on the blank line between the Private Sub cmdToggle_Click() and End Sub lines:

cmdToggle.Caption = "Off"

By adding .Caption to the end of a control’s name you can reference its Caption property. This is also how you reference the values of all the other properties of a control. For example, we could change the position of a button by changing its Top property like this: cmdToggle.Top = 10 (don't type this line!). Now the button would move to a position 10 twips (we’ll talk about twips later) from the top of window.

Now you can test run your program to see how it works so far. But first choose Save Project from the File menu.

To run your program, click the Start button on the Toolbar. It looks like this:

You should see a window with a blue caption bar. Right smack in the middle this window is your cmdToggle button with the caption On in the middle of it (remember when you set the Caption property of the cmdToggle to the word On back in step 3).

Click on the button with the mouse. Now the word On changes to Off. That’s your cmdToggle_Click() procedure in action.

Now stop your program by clicking the End button on the Toolbar. It looks like this:

Not bad. Not very exciting, but not bad.

Remember, the original description of this program was, "you will create a program that displays a sizable window with a single button displayed exactly in the center of it." A Sizable window means that you can grab the borders of the window with a mouse and stretch it or shrink it, thus changing its size.

Run your program again. Click and drag the lower right corner of the window with the mouse and make the window smaller. Does the cmdToggle button remain in the center of the window? No. Our next goal is to make sure that when the window is sized, the cmdToggle button moves to remain exactly in the center of it.

Like individual controls, the form itself also has its own set of built-in event procedures.

If the code window isn’t showing, double-click anywhere on the surface of the form (not on the cmdToggle button), and the Code Window should pop open. To display event procedures of the Form, select Form from the Objects dropdown list box (top of code window on the left). The Private Sub Form_Load() event procedure will appear in the Code window. This is the event procedure that appears by default when you first select the Form from the Objects dropdown listbox. Every control has a default event procedure that appears when you first select it (i.e. Click is the default event procedure of Command Button controls, etc) Any commands entered in the Form_Load event procedure are executed once, when the form is first loaded (when the program is first launched—even before the window actually appears).

A form’s Resize event procedure is executed automatically whenever the size of the form is changed (Note: What is called a form when you’re creating a program, is your program’s window when it runs).

Since the form’s Resize event procedure is executed when the size of the form is changed, this is the logical place to put code that repositions the cmdToggle button so that it remains centered in the form.

To get to the Form’s Resize event procedure, pull down the Procedure drop-down listbox (top of code window on the right) to see all the Event Procedures that come with a Form. Find the Resize event procedure (the list is in alphabetic order) and click on it.

You should now see the Private Sub Form_Resize() procedure heading in the Code Window. The values of the Left, and Top properties of the cmdToggle control are what you need to change in order to adjust the position of the cmdToggle button and keep it centered in the form. Type the following commands to center the cmdToggle button when the form is resized:

cmdToggle.Left = (frmProj1.Width / 2) - (cmdToggle.Width / 2)
cmdToggle.Top = (frmProj1.Height / 2) - cmdToggle.Height

By using the form’s Width and Height properties, it’s easy to calculate the new position of the cmdToggle button. By dividing the frmProj1.Width property in half, you get the exact center of the form horizontally. You need to take into consideration the fact that the Left property of the cmdToggle button control refers to the upper left corner of the button. By subtracting half the width of the cmdToggle button from the horizontal half-way point on the form, we place it exactly centered horizontally. Setting the vertical position of the button with the Top property is done almost the same way. Note: The caption bar at the top of the form is included in the frmProg1.Height value, so we subtract the entire Height of the cmdToggle button to compensate.

Now save the project by choosing the File menu and Save Project before running it. Run your program with the Run button and resize the window with the mouse to see if the cmdToggle button changes position to stay centered. (If it doesn’t, check for syntax errors in your code. Make sure the code above is in the Private Sub Form_Resize() procedure).

That completes the basic assignment.

Some Recommended Enhancements


 

Beginning Visual Basic - Project 1

Properties/Procedures Table

Properties

Object Property Setting
Form Name frmProj1
  Caption Project 1
Command Button Name cmdToggle
  Caption On

Event Procedures

Object Procedure Code
Form Form_Resize() cmdToggle.Left = (frmProj1.Width / 2) - (cmdToggle.Width / 2) cmdToggle.Top = (frmProj1.Height / 2) - cmdToggle.Height
cmdToggle cmdToggle_Click() cmdToggle.Caption = "Off"
(Alternate—Makes the cmdToggle Button’s Caption cycle between On and Off)
cmdToggle cmdToggle_Click() If cmdToggle.Caption = "On" Then
   cmdToggle.Caption = "Off"
Else
   cmdToggle.Caption = "On"
End If