Learn the most popular programming language of the most popular Operating System: Windows

Ad

Coded Statements and Methods

In the preceding procedure, you wrote several coded instructions, which introduced two different programming statements and a method: the Dim statement, an assignment statement, and the Print method.  You also added a remark or comment to your code and used the Private keyword.

The Dim Statement

The Dim statement is used to declare variables and to allocate storage space.  The statement begins with the keyword Dim, as in:

Dim message As String

It declares the variable message as a string of characters. As a string, it can contain characters, including blank spaces and punctuation, as well as numbers.

When typing statements, observe that the Visual Basic editor changes keywords to blue. If your statement is correct, the word Dim and the words As String appear in blue. This tells you that the syntax used in writing the statement is correct. If you make a mistake, as in the following code in which the word String is misspelled, the blue markings will not appear:

Dim message As Sting

The Assignment Statement

With an assignment statement, an equation is used. The value expression on the right side is assigned to the variable on the left. The syntax for the assignment statement is as follows:

[Let] variable = valueexpression

The syntax states that the keyword Let is optional. The dollar sign ($) is also optional, you could have written the following:

message$ = "Welcome to Visual Basic"

Because the dollar sign ($) is optional, you could have written the following, for message has been declared as a variable of type String:

message = "Welcome to Visual Basic"

In general, use a dollar sign to help distinguish a string variable from another type.

A string expression must begin and end with quotation marks. If you write the following, omitting the quotation marks, you will be in error:

message = Welcome to Visual Basic

The Remark Statement

In Visual Basic, any statement that begins with a single quotation mark (') or the keyword Rem is a remark, as follows:

Rem The Print command is used to display a message

Remarks or comments are used to describe the purpose of a procedure as well as key features of a procedure. Use remark statements to document how your code works and to provide other type of important coding information. Also, be careful when writing the statement. Use the apostrophe (') which is the same as single quotation mark and shares the quotation mark (") key, and not the grave accent (`), which can be found on the tilde (~) key. In writing the procedures, we used the apostrophe rather than Rem. This enables us to place remarks to the right of an instruction, as in the following example:

Print 'This instruction displays a blank line

When writing remarks, use the color code returned by the editor to determine whether your statements are correct or incorrect. A correct remark statement will, by default, be shown in green.

The Private Keyword

All control procedures are preceded by the Private keyword by default. This keyword makes the procedure accessible only in the form module in which it is declared. The meaning and use of the Private keyword, as well as other keywords that can be used in procedure declarations, are discussed in detail under "Defining the Scope of Variables and Procedures," when you consider the topic of variable and module scope. For the time being all procedures you write will use the Private keyword.

The Print Keyword

The single method used in Exercise 3.2 was the Print method. A method differs from a statement, such as an assignment statement, by specifying the behavior of an object. The following statement features a period (.) to separate the object from the action to be taken:

Form1.Print "Message to be printed"

That, in turn, is followed by a space, so that the following instruction would be in error:

Form1.Print="Message to be printed"

The syntax used for the Print method itself is quite complex and deserves special attention. You consider that notation next. Once you understand this syntax, you will be able to understand the syntax designed for all methods.

Share:

Coding Event Procedure for Control

Coding an Event Procedure for a Control

Adding a control to a form and setting the control properties set the scene for adding a procedure.  Remember that a control will do nothing to an event-oriented environment unless an event procedure is attached to it.  To add to this concept, more than one event can be associated with a single control, as with a form.  In the next exercise you will examine the various event and alternatives for a single control.

Controlling Naming Conventions

When adding an event procedure, a default name is always assigned to the form or control unless you decide to change it.  For example, the first command button added to a form is named Command1, and the second is Command2. In this text, we ask you to follow a command syntax by adding a name prefix to a control (and many times to forms).  For example, if you decide to add a command button to a form and change the command caption to Start, you would name the control cmdStart.  The cmd is the command prefix.  The prefix always tells you what specific control you are working with.

The exception to the above rule is when you are working with labels that have no effect on the input or output to a program.  Because changing the name of each control takes considerable time, you should often leave label conventions (Label1, Label2, and so on) alone, unless the content of a label is determined by a procedure.  This separates labels whose content is determined by a procedure from those whose content is not determined by a procedure.

Table 3.1 shows the controls, the default names and the name prefixes that are used for the 12 controls.

Table 3.1 The 12 Controls
ControlDefault NameName Prefix
Text BoxText1txt
LabelLabel1 txt
List BoxList1lst
Combo Boxcombo1cbo
Picture Boxpicture1pic
FrameFrame1fra
Option Buttonoption1opt
Command Buttoncommand1cmd
Check Boxcheck1chk
Image Image1img
Horizontal Scroll BarHScroll1hsb
Vertical Scroll BarVScroll1vsb

Exercise 3.2 Adding a Procedure to a Command Button

For this exercise, you write a procedure and attach it to a command button. Figure 3.4 shows how the form will look when you run the program.

Figure 3.4

In this display, the user is expected to click the Start button to display the message on the form.

  1. Begin a new project or continue the last.
  2. Add a command button to the form.
  3. With the form active (not the command button), press F4 to reveal the properties box.  Make the following change:

    Caption = A Printed Message

  4. With the command button active, press F4 to reveal the properties box. Make the following changes:

    Caption = Start

    Name = cmdStart

  5. With the command button still active, double-click to open the Code window.  Enter the following code, between the Private Sub cmdStart_Click() and the End Sub instructions:
    Private Sub cmdStart_Click()
    'The Start command button is used to display a message
    Dim message As String
    Print
    message$ = "Welcome to Visual Basic" Print Spc(20); message$ ' prints 20 spaces followed by the message End Sub
  6. Save the project.
  7. Close the Code window and run the program.  Click the Start button.
  8. Exit and open the Code window to examine the other types of events that can be assigned to the cmdStart control.  For example, instead of writing a cmdClick() procedure, you might write a MouseDown() procedure, such that when the user presses the mouse button, the message is displayed.  As another alternative, write a MouseUp() procedure.
Share:

Setting Properties for a Control

After adding a control to a form, the properties of the control can be modified.  Control properties work in the same way as form properties:  They can be used to change the appearance or the behavior of the control.  Figure 3.3 shows the Properties dialog box for a command button.  Like a form, you can set a wide variety of options for a command.

Besides Caption and Name,command button properties include ways of changing the appearance of the text on the button, the size of the button, and even how you want the cursor to appear when it is placed over the button (the MousePointer property).  You cannot change the color of the button, as the next exercise demonstrates.

Figure 3.3 The properties box for a command button contains a Caption and a Name property and a host of other properties.

Exercise 3.1 Examining the Control Property Box

In this short exercise, you add a command button to a form and change its properties.

  1. Open a new project.
  2. Double-click the Command Button control.  If you place the wrong one on the form, select Edit, Delete to remove the control from the form.
  3. With the Command1 button on the screen (see Figure 3.3), move it to the left-hand side of the form.
  4. Change the BackColor property using the BackColor palette to change the color.
  5. Run the program. What does the BackColor setting change?
  6. Click the form and the Command button. Can you determine why nothing happens? Because you have not indicated what action (that is, what event) is to take place when the button is clicked, the piece missing is a procedure.
  7. Exit to return to the form.
Share:

Adding a Control to a Form and Setting its Properties

With the preceding brief overview of several different types of controls fresh in your mind, consider the procedure for placing a control on a form, and once positioned, changing the properties of a control.  As a rule, the properties of a control should be  set before event procedures (that is, coded procedures)  are written.  This practice enables you to prototype your design before you begin the code-writing process.  A prototype in this instance is a partial, but not full, representation of your finished design.

Adding a Control to a Form

There is a long procedure and a short procedure for adding a control to a form, and each method has merit.  The following is the long procedure:

  1. Select the control you want from the toolbox.
  2. Make the form active by clicking it to indicate where you want to place the control.
  3. Drag the handles on the control to size it the way you want.

The short procedure is simply the following two steps:

  1. In the toolbox, double-click the control you want.  This places the control on the active form.
  2. Move and change the size of the control as needed.

Figure 3.2 shows how you move a control.  Click the center of the control, and drag the control to a new position.  To change the size of the control, click one of the handles (the small black boxes), and drag the control in a horizontal, vertical, or diagonal direction.

Figure 3.2 To size a control, use the square handles on the sides. To move a control, click the center of it and drag it with the mouse.

When placing option buttons within a frame on a form, the longer procedure binds the control to the frame container. (You are asked to use a frame in next section "Learning to Think Visually.")

Setting Properties for a Control

After adding a control to a form, the properties of the control can be modified.  Control properties work in the same way as form properties:  They can be used to change the appearance or the behavior of the control.  Figure 3.3 shows the Properties dialog box for a command button.  Like a form, you can set a wide variety of options for a command.

Besides Caption and Name,command button properties include ways of changing the appearance of the text on the button, the size of the button, and even how you want the cursor to appear when it is placed over the button (the MousePointer property).  You cannot change the color of the button, as the next exercise demonstrates.

Figure 3.3 The properties box for a command button contains a Caption and a Name property and a host of other properties.

Exercise 3.1 Examining the Control Property Box

In this short exercise, you add a command button to a form and change its properties.

  1. Open a new project.
  2. Double-click the Command Button control.  If you place the wrong one on the form, select Edit, Delete to remove the control from the form.
  3. With the Command1 button on the screen (see Figure 3.3), move it to the left-hand side of the form.
  4. Change the BackColor property using the BackColor palette to change the color.
  5. Run the program. What does the BackColor setting change?
  6. Click the form and the Command button. Can you determine why nothing happens? Because you have not indicated what action (that is, what event) is to take place when the button is clicked, the piece missing is a procedure.
  7. Exit to return to the form.
Technorati Tags: ,,
Share:

Adding Controls and Event Procedures to Form Modules

So far you have learned how to add controls to a form, but you have not yet done it.  In this chapter, you add controls to form modules and attach event procedures (Visual Basic code) to a control.  How can you do this before you understand the Visual Basic language?  Whether you knew it or not, you wrote some Visual Basic code earlier. Writing and Running Your First Visual Basic Program.”  The Print method, for example, is part of the Visual Basic language.

In this section, you will write several additional Visual Basic instructions.  The instructions take you through the steps slowly to help you gain confidence in working with the language.

You will master several tasks in working through this section, including how to

  • add a control to a form,
  • change the properties of a control,
  • add a procedure to a control,
  • write an assignment statement,
  • use the Dim and remark statements
  • use the Print and Cls methods,
  • assign text to a text box,
  • assign a caption to a label.

Objectives

The four objectives of this section introduce you to adding controls to a form and writing event procedures to display information:

  1. Understanding standard toolbox control objects
  2. Adding a control to a form and setting its properties
  3. Coding an event procedure for a control
  4. Changing object properties with coded statements

Understanding Standard Toolbox Control Objects

Remember from Running a Visual Basic Program. that a control is an object attached to a form module.  The designers of Visual Basic decided to provide a number of standard controls (located on the toolbox) to represent the standard types of objects to be added to a form.  You can also purchase custom controls, which have an .OCX extension when installed.  To help you remember the differences among controls, tools are grouped into four initial categories.

  1. Text controls
  2. Containers for groups of controls
  3. Button controls
  4. Scroll bar controls

There are still other controls on the toolbox, but the preceding four categories represent a significant number.  Remember that by letting your mouse cursor linger a moment over one of the controls in the toolbox, a ToolTip will appear to identify it.

Text Controls

The following four controls deal primarily with text.  The left-hand side of Figure 3.1 shows how these controls appear on a form.

  • Text Box control – Places text entered by the user on a form.  Information that the user types appears in the text box.  A text box can also contain default text to enable the user to bypass the control if the text does not need to be changed.
  • Label control – Displays text entered by the program designer.  The user cannot type or directly change a label.
  • List Box control – Displays a list of items.  The user can make one or more selections from the list.  With a list box, the Visual Basic designer can add or remove items from a list.
  • Combo Box control – Combines the features of a list box and a text box.  This control gives the user the choice of selecting an item from a list or entering a value from the keyboard.

Two of the text control objects – the text box and the combo box – enable the user to enter data into a program.  On the other hand, a user can make a selection from a list box, but can’t enter data.  Similarly, a label cannot be charged; however, because labels are read-only, they are used often to display the results of processing.

Containers

Containers house or contain (like a bucket) a set of controls.  There are two types of container controls, as follows:

  • Picture Box control – Used to store or contain a graphic image, such as a bitmap.  It is typically used with a frame.  It can also serve as a container for other controls, such as a group of images or a toolbar.
  • Frame control – Used to provide a rectangular area on the form where other controls can be placed as a group.  It generally serves as a container for a group of buttons, such as a set of option buttons.

The middle portion of Figure 3.1 shows how these controls appear on a form.

Buttons

Buttons are controls that users click to turn on or off.  The button manipulation action (for example, a single mouse click) invokes an action an event.  The middle portion of Figure 3.1 shows option buttons, check boxes, a command button, and an Image control.  The following describes the button controls:

  • Option Button control – Enables the user to make one selection from a group of choices, similar to a multiple-choice question.  Several option buttons are usually grouped inside a frame or picture box.  When one option within a group is selected, all other options are canceled.  This is called exclusive choice.  You should use option button when you want the user to make only one selection.
  • Check Box control – Enables the user to turn an option on or off, or set a value to true or false.  Check boxes can also be grouped.  However, unlike option buttons, any number of check boxes can be selected.  This is called non-exclusive choice:  Selecting one does not cancel the others.
  • Command Button control – Places a button on a form that the user clicks to invoke an event.
  • Image control -  Used to place an image on the screen.  A user can click the image like a command button to invoke an event.  Several Image controls, arranged as a group, can be used to design a toolbar.

Scroll Bars

Scroll bars enable the user to examine a list when the entire list does not fit on a screen.  Both horizontal and vertical scroll bars can be added to a form (see the right-handed side of Figure 3.1), as follows:

  • Horizontal Scroll Bar control – Provides for easy navigation through a long line of information, or enables the user to set speed, quantity, or quality.  Placement is across the screen.
  • Vertical Scroll Bar control – Same at the horizontal scroll bar except that placements runs down the screen.

The 12 controls described in this section do not take into account all of the standard controls found in the toolbox.

Share:

Compiled Application from Standard EXE Project

This final objective asks you create an executable file from a completed Visual Basic application.  Two options are available: Under the Compile tab of the Project Properties dialog box, you can select Compile to P-Code or Compile to Native Code (see Figure 2.10).  Compiling to native code is the default.

Figure 2.10The Compile tab of the Project Properties dialog box enables you to control the way in which you compile your completed application.

Interpreted P-Code

By selecting P-Code, the modules of your Visual Basic application are compiled into what is called pseudocode or false code.  An interpreter program that then produces machine language instructions reads the coded instructions.  All versions of Visual Basic prior to Visual Basic 5.0 were interpreted from P-Code.

Interpreted programs offer some advantage.  Applications can be designed rapidly because new code can be tested immediately, without time-consuming compilation.  They also offer some security advantages in networked applications.  You can rely on the interpreter to serve as a buffer between an application and computer hardware.  This is the security model built into the Java programming language, for example.  To their disadvantage, interpreted programs tend to run slower than compiled programs.

Compiled Native Code

With Visual Basic 5.0, you can create native code compiled applications:  The compiler takes the modules of your project and creates a machine language compiled application.  Although the native code executable does not require interpretation, it still depends on other files to run.  These files consist, mainly, of the object linking and embedding (OLE) libraries that make up the ActiveX architecture upon which Visual Basic is based.

One way to think about the difference between interpreted and compiled programs is to compare it to translating a letter from English to German (or another language).  A compiled program translates the entire letter once, producing machine-language instructions.  An interpreted program translates each letter every time the letter is read, producing P-Code, which is then translated into machine language.

The Make Tab of the Project Properties Dialog Box

When you decide to create an executable, the Make tab of the Project Properties dialog box comes into play.  The Make tab presents general attribute options for your executable (see Figure 2.11), including the title of the application, the icon used to represent the application when it is minimized, and different version options. The Make tab also enables you to set command-line arguments for your application should you decide to use them.

Figure 2.11The Make tab enables you to set version numbers, version information, application attributes, command-line arguments, and conditional compilation arguments.

Exercise 2.9  Creating an Executable Application

This exercise asks you to create a make file from the Happy Birthday application created in Exercise 2.8.

  1. Open Exercise 2.8 if it is not on the screen.
  2. Choose File, Make Project2-8, if this reflects the name you gave your project.
  3. When the Make Project dialog box opens, select a file name, such as BDAY1.EXE, and click OK.  That's it. You have created a native code executable file. Remember that native code is the default.
  4. Choose File, Make Project2-8 again, and when the dialog box opens, click Options.
  5. Click the Compile tab.
  6. Click Compile to P-Code, and click OK to return to the Make Project box.
  7. Select a different file name, such as DAY2.EXE.
  8. Close Visual Basic, and start Windows Explorer.  Locate both DBAY1.EXE and BDAY2.EXE.  Click BDAY1.EXE to run the program.  Close BDAY1.
  9. Click BDAY2.EXE to run the program.  Close BDAY2.
Share:

Writing Visual Basic Instructions-2

Exercise 2.6  Changing the Font Size Property

In this and the next two exercises, you change the properties of the form used in Exercise 2.5.

  1. Choose File, Open Project, if necessary, and select View, Project Explorer, or click the Project Explorer icon to open the Project window.  Click View Form.
  2. Click the form to give it the focus, and press F4 to open the Properties dialog box.
  3. Click font and change the font size to 18 points (or to another size if the size is not available on your system).
  4. Run the program.  Click to display the first sentence.  Press a key to display the second sentence.
  5. Exit to continue with the next exercise.

Exercise 2.7  Changing the Font Style Properties

In this exercise, use the form from Exercise 2.5 once again.

  1. Open the Properties dialog box and open the Font dialog box by double clicking the Font property.  Change the Font to Bookman Old Style (or another font if your system does not have this font installed).
  2. Change the style to bold and italic.
  3. Run the revised program.  Click to display the first sentence (it should be in bold and italic).  Press a key to display the second sentence.
  4. Exit and save your project at this time.  The next exercise asks you to begin a new project.

Exercise 2.8  Adding a Message to a Form and Changing Property Settings

In this exercise, you write a new procedure and change properties.

  1. Open a new project.
  2. Add the following Form_Click() Visual Basic procedure to the form:
    Private Sub Form_Click()
    'This procedure will display a Happy Birthday message
    Print "                 HAPPY"
    Print "                 BIRTHDAY"
    End Sub
    
  3. Change the following form properties:
    PropertySetting
    Backcolor Palette= &H00FF00FF& (light purple)
    BorderStyle= 1 'Fixed Single
    Caption= Today is the day
    Font Style= Italic
    Font= Arial
    Font Size= 24
    ForeColor Palette= &H00FF0000& (blue)
    WindowState= 2 'Maximized
  4. Run your program.
  5. Exit and save your program. Give the form a unique name, such as BDAY.FRM. Give the project a similar name, such as BDAY.VBP.
Share:

Writing Visual Basic Instructions

The final type of window discussed here is the Code window.  To open the Code window for a form, click the Project Explorer and click View Code, or choose View, Code.  This opens the window shown in Figure 2.7.  The object shown is the Form; the procedure is shown as Load().  The title bar reads Form1 because you have not changed the name of the form.

Figure 2.7

This Code window shows the start of a Form_Load() procedure.

The Code window contains the first two coded instructions, which are entered for you.  The first combines the name of the object with the name of the event procedure.  This coded instruction is shown in the following example, in which Load() is a special type of event:

Private Sub Form_Load()

It occurs when a form is first loaded.  However, suppose you want to change the event from Load() to Click().  By selecting Click (click the procedure list box and scroll to Click, as shown in Figure 2.8), the first coded instruction changes to the following, in which Click() is another type of event:

Private Sub Form_click()

It is triggered by a mouse click.

Figure 2.8

The Code window now shows the start of a Form_click() procedure.

The event has now been changed from occurring at the time the form is loaded to the time when the form is clicked, with the user controlling the time of the event with the click of the mouse.

The ending instruction stays the same.  It reads as follows, which means the end of the procedure (sub):

End Sub

Exercise 2.4  Adding a Click() Procedure

In this exercise, you begin a new project.

  1. Choose File, New Project and open a Standard EXE project.  If the last project is still on-screen and has not been saved, you will be asked if you want to save changes to P2-3.vbp? Click No, unless you have already saved it.  Either way will not lead to problems.
  2. When Form1 appears, double-click to open the Code window.
  3. Change the Project name to Project2_4.
  4. Change the procedure name from Form() to Click() in the procedure list box.

    Your code should read as follows:

    Private Sub Form_Click()
    End Sub
    
  5. Type the following to create the procedure:
    Private Sub Form_Click()
    'This procedure will display a message on the form
    Print
    Print
    Print "When you click, look at what happens!"
    End Sub
  6. Close the Code window by double-clicking the Control box icon.
  7. Choose Run,Start;click the Start icon on the toolbar; or press F5 to run your procedure. When Form1 appears, place the mouse pointer on the form and click. What happens?
  8. Click the form again. What happens? It makes you want to click forever doesn't it?
  9. Choose Run, End from the menu bar or press the End button on the toolbar to return to the design of Form1.
  10. Save this form and project. You can call the Form F2-4.frm and the project P2-4.vbp if you want to use them in later exercises; however this is not necessary. Continue with the next exercise using the same form.

Exercise 2.5 Adding a KeyPress() Procedure

In this exercise you add a second procedure to a form. Figure 2.9 shows the revised form. This exercise assumes you have completed Exercise 2.4 and are using that form.

Figure 2.9

Adding a KeyPress() procedure to the form places more than one procedure on the same form.

  1. Choose View, Code from the menu bar. The code you wrote for Exercise 2.4 should appear.
  2. Choose KeyPress from the Procedure list box, and observe what happens to your code.
  3. type the following to complete this procedure:
    Private Sub Form_KeyPress (KeyAscii as Integer)
    'This procedure will display a different message on the screen
    Print
    Print
    Print "    When you press a key, look at what happens!"
    End Sub
  4. Close this procedure (using the Control menu icon) and run the revised program. There are four ways to run your program:
    • Choose Run, Start.
    • Choose Run, Start with Full Compile.
    • Press F5.
    • Press the Start button on the toolbar.

    This time, press F5 to start your program; then as a test, do the following:

    1. Click the form.
    2. Press a key.
    3. Press a second key.
  5. Click the End button on the toolbar to stop your program a different way, or choose Run, End to stop the program.
  6. When you are returned to Form1, double-click the form to open the Code window. What code appears?
  7. Scroll through the list of procedures in the Procedure menu. Coded procedures are displayed in bold.
  8. Save this form and project at this time. You will be asked to work with the form and project in the next several exercises, but it is wise to save your work periodically. You can save your form as F2-5.frm and your project as P2-5.vbp to keep your examples in sequence. Name the project Project2_5 before saving.
Share:

Disabling the Minimize Button

With the first two border styles, the Minimize button appears unless it is disabled by the Minbutton property to change the setting to False.  (With this property, there are only two choices: True and False.)

Disabling the Maximize Button

With the first two borderstyles, the Maximize button appears, unless it is disabled.  To disable the button, double-click the MaxButton property to change the setting to False. (Like MinButton, only two choices are available with MaxButton: True and False.)

Disabling the Control Box

With the first three border styles, the control box appears unless it is disabled.  To disable the box, double-click the ControlBox property to change the setting to False. (The two settings for ControlBox are True and False.)

Changing the Window State

The WindowState property determines the appearance of the form at runtime.  Table 2.3 shows its three settings.

Table 2.3 The Settings for the WindowState Property
ValueSettingDescription
0 Normal The form appears in normal size (the default).
1 Minimized The form is minimized and appears as an icon (either on the taskbar or above it) when the application is run.
2 Maximized The form is maximized and expands to fit the entire screen when the application is run.

Changing the background Color

Part of the enjoyment of working with Visual Basic is the ease with which colors can be added to a form.  Color settings are expressed in hexadecimal notation (base 16). The designers of Visual Basic did not expect you to work with hexadecimal numbers and instead provided a color palette.  To open the palette, double-click the Backcolor setting and click Palette.  When the Color palette appears, click a color to change the background color of the form.  Following the click, the hexadecimal number assigned to the color appears in the text box.

Changing Font Properties

When working with text, Visual Basic enables you to change the font (or text style) you are working with.  To determine which fonts are available on your system, open the Properties window, highlight Font, and click the ellipsis button to the right.  A dialog box appears for setting numerous font properties, including Name, Bold, Italic, Size, StrikeThrough, and Underline.

Changing the Foreground Color

The ForeColor property determines the color of the text and graphics to be displayed.  This differs from Backcolor, which determines the background color of the object.  To set this property, double-click ForeColor and click Palette.  Make the color selection using the palette.

Changing the Startup Position

The StartUpPosition property specifies the position of the form when it first appears.  Table 2.4 shows its four settings.

Table 2.4 The Settings of the StartUpPosition Property
ConstantValueDescription
vbStartUpManual0No initial setting specified
vbStartUpOwner1 Center on the item to which the UserForm belongs.
vbStartUpScreen 2Center on the whole screen.
vbStartUpWindows3Position in upper-left corner of screen.
Share:

Opening the Properties Window and Changing Form Properties

Besides a Project Explorer window, each form (or control) contains a Properties window.  As stated in Running a Visual Basic Program, a property is a named attribute of an object.  Properties are used to change the appearance or behavior of objects.

Figure 2.6 illustrates the default Properties dialog box for a form.  If this box is not visible, you can bring it into view by pressing the F4 function key, or choosing View, Properties Window.  With the form having the focus, press your right mouse button and drag down the Properties list.

Figure 2.6  
The Properties dialog box of a form contains the built-in form attributes that you can change.

Over 50 properties can be set for a form.  Although this number seems overwhelming at first, some properties are used so frequently that they represent an initial set to remember.

Form Properties

Caption

Name

BorderStyle

MinButton

MaxButton

ControlBox

WindowSize

BackColor

FontName

FontSize

FontBold

FontItalic

FontStrikethru

FontUnderline

ForeColor

StartUpPosition

To simplify this list somewhat, the items can be grouped by their uses:

  • Seven properties deal with the way in which the form or text appears on the display screen (Caption, BorderStyle, MinButton, MaxButton, ControlBox, WindowSize and StartUpPosition).
  • The identification of an object is specified by the Name property.
  • Font settings are controlled using the Fonts dialog box (FontName, FontSize, FontBold, FontItalic and FontStrikethru).
  • Color settings (ForeColor and BackColor) use a special palette.

There are three ways to change most property settings:

  • Click the property to highlight it, and enter (type in text) the new property setting in the text box.
  • Double-click the setting to view the alternative settings.
  • Click the down arrow to open the drop-down menu for property settings.

Properties for fonts and color launch a separate dialog box for you to enter settings.

Changing a Caption

The Caption property enables you to change the title that appears on the top of a form.  Instead of Form1, use the Caption property to add a title.  To change the caption, select Caption in the Properties dialog box and type the new title in the text box next to the property name.

Changing a Form Name

The Name property specifies the name of the form to be used in writing Visual Basic code. Remember the following rule: The name, not the caption, is the identifier.  When writing coded instructions, the Name property appears as the object name.  To change the name, select Name in the Properties dialog box and type the new name.

Changing the Border Style

The BorderStyle property enables you to change the appearance of the form’s border.  To change the border setting, double-click the current setting to reveal other choices, or click the down arrow to open the drop-down list of the six options.

If you are uncertain about the six border choices and their precise effects, click BorderStyle to give it the focus in the Properties dialog box, and press F1 (the Help function key).  Visual Basic Help displays the six style choices and explains their effects, as shown in Table 2.2.

Table 2.2 The Settings for the BorderStyle Property
Setting Style Description
0 None No border or border-related elements.
1 Fixed Single Can include Control menu icon, title bar, Maximize button, and Minimize button.  Resizable only using Maximize and Minimize buttons.
2 Sizable The default.  The size can be changed using any of the optional border elements listed for setting 1.
3 Fixed Dialog Can include Control menu icon and title bar; can’t include Maxiimize or Minimize buttons.  Not resizable.
4 FixedToolWindow Under 16-bit versions of Windows and Windows NT 3.51 and earlier, behaves like Fixed Single.  Does not display Maximize or Minimize buttons.  Not resizable.  Under Windows 95, displays the Close button and displays the title bar text in a reduced font size.  The form does not appear in the Windows 95 taskbar.
5 SizableToolWindow Under 16-bit version of Windows and Windows NT 3.5 and earlier, behaves like sizable.  Docs not display Maximize or Minimize buttons, Resizable.  Under Windows 95, displays the Close button and displays the title bar text in a reduced font size.  The form does not appear in the Windows 95 taskbar.

The online Help is one of Visual Basic’s strongest features.  Remember, the F1 key is your friend!  Use it often.  The language is just too vast to remember all of it.

Share:

The concept of Focus

The concept of focus is important in Visual Basic.  The object that is selected (such as a form, control, or menu bar selection) is said to have focus.  In order for Visual Basic to know what file to save, it is necessary to click the object to give it focus, making it the active object.  Likewise, to remove a file, the object must be given focus.  To remove a file, open the Project window, click the file to remove, and choose File, Remove and the name of the file to remove will also appear.  An alternative is to display the Project Explorer, click the file that you want to delete, and right-click to produce the shortcut menu shown in Figure 2.3.  We discuss the concept of focus at length later.  There are even unique events, such as Gotfocus and LostFocus, that deal with this issue.

Figure 2.3 Display the Project Explorer and right-click to reveal several file optiions, including a command for removing a file from a project.

Exercise 2.2  Using the Remove and Add Commands

This exercise assumes that you completed Exercise 2.1 and saved the form as F2-1.frm.

  1. Open a new Standard EXE project, and change the name of the project to Project2_2 (click Project, Project1 Properties).
  2. Choose Project, Remove Form1.Form1 must have the focus because it is the only object assigned to the project.
  3. Choose Project, Add File.  Navigate through Windows to the location where you saved F2-1.frm, and add this form to your Project (see Figure 2.4).

    Figure 2.4

    The Add File dialog box lists saved forms that can be added to a project.

  4. Open the Project Explorer Window, and give form F2-1.frm the focus.
  5. Choose File, Save File As (or click the right mouse button).  When the dialog box opens, navigate to the location where you want to save the file, and name it F2-2.frm.
  6. Open the Project Window again and observe what happens.  The name of the form has been changed and assigned to the new project.
  7. Choose File, Save Project As.  In this instance, you are not asked to name the form because it has already been named and saved.  Instead, you are asked only to name the project, which we named P2-2.vbp.

Other File Menu Commands

Besides the four Project menu commands and the two file commands found on the File menu, the latter also contains the Print and Print Setup commands and the Make Project1.Exe commands, as follows:

  • Print – Choose File, Print to display several options for printing information about a project (see Figure 2.5).  You can print the form image, code, or the form as text, and you can choose to print information for a module or for the entire project.
  • Print Setup – Choose File, Print Setup to launch the standard Windows Print Setup dialog box.
  • Make Project1.Exe – Choose File, Make Project.Exe to create an executable application.  Project modules are compiled into a single .EXE file.  This file is either a P-Code interpreted executable or a native code executable file.  (The two code formats are explained in “Interpreted P-Code,” and “Compiled Native Code,” later.)

Both types of executables require runtime files.  The Visual Basic Setup Wizard can help you determine which runtime file your application requires.

Figure 2.5 The Print-Project dialog box enables you to choose the parts of an application that you want to print.

Exercise 2.3  Using the Print Command

This exercise is designed to show you the type of information printed for a project.

  1. Open a new Standard EXE project.
  2. Choose File, Print.
  3. When the dialog box appears, click Current Project, Form Image, Code and Form as Text.
  4. Click OK.

What is the difference between the Form Image and the Form as Text choice!  Why is there no computer code?

Share:

Naming a Project

Each time you begin a new project, the default name, Project1, appears at top of the form.  Unless you change the name, every project you work on will be named Project1.  To change the name, choose Project, Project1 Properties (see Figure 2.2), and type a new project name.  For example, you might enter Project2_1 for this initial project.

Figure 2.2

The Project Properties dialog box is used to change the name of the project from the default, Project1, to a name of your choosing.

Exercise 2.1 Using the Save Project As Command

This exercise asks you to do very little, but it does introduce you to the file naming conventions. Start Visual Basic, and perform the following steps:

  1. Open a Standard EXE new project.
  2. Choose Project, Project1 Properties and change the name of the project to Project2_1. Click OK. This new name should appear on the topmost title bar of Visual Basic.
  3. Choose File, Save Project As. A dialog box appears and asks if you want to save the file as Form1.frm. If you click Cancel, the form is not saved and you have to rebuild it if you need it. Imagine that you spent an hour perfecting a form. Unless you save it, your work will be lost.
  4. Before you click Save, navigate to the location where you want to save the file, and assign a name to the form. Assign a unique name - something other than the default, Form1.frm. You can use the notation F2-1.frm to indicate that this form goes with exercise 2.1 (not very clever, but it works). A more descriptive name would be better.

    If you want to store the form on a diskette placed in the a: drive of the computer, navigate to the drive and type F2-1.frm.

  5. After the form has been saved, a second dialog box appears asking you to assign a name to the project. Again, assign a unique name (not the default, Project1.VBP). You can call it P2-1.VBP to indicate that this project goes with Exercise 2.1. Here too, a descriptive project name would be better.

If you want to save the project on a diskette placed in the a: drive of the computer, navigate to the drive and type P2-1.VBP

The Add File and Remove File Commands

Files can be added to, or removed from, the .VBP project file using the file commands contained on the Project menu. When adding or removing files, keep in mind that you are adding or removing files from a project. The following are two Project menu commands that you will use often in this book:

  • Add File - Choose Project, Add File to open a dialog box (see Figure 2.4) that enables you to navigate the Windows file directory to identify a previously saved file and to add the file to a project, for example, an .FRM (form), .BAS (coded module), .CLS (class modules), or .RES (resource file). This command is especially important when you use a file built for a different project. Simply identify the file name, and click OK.
  • Remove <Name of File> - Choose Project, Remove <Name of File> to remove the file from the current Project that is active (has the focus, a term that is described next).

Other Project menu file commands include Add Form, Add MDI Form, Add Module, and Add Class Module. These enable you to add new types of forms and modules to a project.

The Save File and Save File As Commands

The following are two File menu commands that are used to save a particular file rather than an entire project:

  • Save File - Choose File, Save File to save the form or module that is active (has the focus). If the file has previously been saved, this command updates the file. If the file is new, this command prompts you for the name of the file and, once entered, adds the file to a project when the project file (.VBP file) is next saved.
  • Save File As - Choose File, Save File As to save the current file to a disk. This option always prompts you for the file name. Like the File, Save Project As command, File, Save File As is used to save a file for the first time or to save a copy of an existing file.

You will find file commands most useful when you want to use the same forms and modules in different projects.  There is nothing to prohibit you from using the same form in dozens of projects because each form is saved as a separate file.

Share:

Learning How to Manage Visual Basic Projects

In this section, you learn how to open and save a project, add and delete files from the Project window, give an object focus (further explained in later section “The Concept of Focus”), and use the other File commands provided with Visual Basic.  You will also work through several exercises to rest your knowledge of the concepts presented.

Opening, Saving, Adding and Removing Projects

Whenever you open Visual Basic, you always start a new project.  However, there are File commands that enable you to work with both old and new projects, and File and Project commands for working with old and new files.  The File menu on the menu bar contains six commands designed for managing projects, as follows:

  • New Projects – Choose File, New Project to start a new project.  If you are working on a project, this command prompts you to save the current project.  It then closes the current project to enable you to start a new one.
  • Open Project -  Choose File, Open Project to open a saved project.  Before opening a project, this command asks if you want to save a current project if one exists.
  • Add Project – Choose File, Add Project to open a saved project and add it to another, provided one exists.  A Visual Basic application can contain any number of projects.
  • Remove Project – Choose File, Remove Project to remove the selected project from a project group.
  • Save Project As – Choose File, Save Project As to save the current project to a disk.  This option always prompts you for a project name.  Use this command to save a project for the first time or save a copy of an existing project.  When first saving a project, you are asked whether or not you want to save each form and module associated with a project.

    For each form or module, you can assign a name.  You should name each form with a name other than the default name (such as form1.frm and form2.frm); otherwise, you will design over the form when you start a new project and find it impossible to retrieve the form you thought you had saved.  You should also name each project with a unique name, or else Visual Basic will assign every project the same default name.

  • Save Project – Choose File, Save Project to save the current project to a disk.  this option saves all forms and modules as separate files.  It creates a file with .VBP (Visual Basic Project) extension.  If the project is being saved for the first time, this command prompts you for the project name.  If saved earlier, it updates the .VBP file.

The .VBP file is saved as text or in ANSI (American National Standards Institute) format.  This allows you to inspect its contents with any text editor.  Each project contains one – and only one - .VBP file, which provides a description of the project, showing the names of the stored files and other descriptive information.

Share:

Understanding the Concept of a Visual Basic Project

Every Visual Basic application is defined and saved as a project.  Each project, in turn, consists of a collection of files.  These files can include modules, insertable objects, and a single resource file.  Projects themselves are tracked by a project file, which has a .VBP extension.

Form modules, as discussed earlier are first seen as a windows with a caption, but little else.  From modules contain coded instructions called procedures for the form itself and for the controls and insertable objects placed on the form.  Other modules include standard modules and class modules.  You will learn the differences among these types of modules as you progress.

The tools of the toolbox represent controls and insertable objects.  The toolbox can be made visible or invisible by choosing View, Toolbox.  When visible, the toolbox contains a set of icons – each representing a standard or a custom control.  A Visual Basic project always includes a set of standard controls and can also include custom controls.  Each custom control has an .OCX extension.  In this section you are asked to write some beginning Visual Baisc procedures for forms.  In “Adding Controls and Event Procedures to Form Modules,” you will add procedures for stand controls.

Projects can also include a resource file, which can contain either binary data, such as images and sounds, or string data.  Resource files need to be created by a Windows resource compiler (typically a C or C++ language compiler), or you can use the resource compiler bundled with Visual Basic.

The Files that Make Up a Stanbdard EXE Project

In working with Visual Basic, you are asked to work with different types of files.  Each file type is given a unique file extension, which enables you to identify it.  Visual Basic contains over two dozen types of files, each of which has a different extension.  The Table below shows eight common file types contained within a project, their extensions, and their meanings.

Table 2.1 Common File Types
Type of File Extension Extension
Standard Module .BAS Each coded module is saved as a file
Class Module .CLS Each class module is saved as a file
Form Module .FRM Each form is saved as a file
Binary .FRX Each Icon or Picture property value is saved by Visual Basic in .FRX form
Log .LOG A file for logging load errors.
Resource .RES A project can have a single resource file for storing binary and string data
Project .VBP Each project is saved as a file.
Workspace .VBW Each workspace for a project is saved as a file.

This file notation is used throughout.  When you save a form, it is saved with a .FRM extension, and all event procedures written for that form are also saved in the .FRM file.  Because procedures are not saved as separate files with their own unique extension, they become bound to forms.  When you write and save a coded standard module, it is saved with a .BAS extension.  Coded modules are thus different from event procedures written for forms.  Coded modules are not bound to forms.

The Project Window (Project Explorer) in the Visual Basic Design Environment

Whenever you begin a Visual Basic program, you begin a new project.  Each project can contain several forms, several standard and class coded modules, and custom controls.  The Project window displays a list of all modules assigned to a project.  Whenever you begin a new project, a default Project window is created (see Fiigure 2.1) .  If the window fails to appear or is hidden, choose View, Project Explorer; press Ctrl+R; or click the Project Explorer icon.  In addition, your environment can be set to remove the docking of the Project Explorer.  This setting is controlled by choosing Tools, Options, clicking the Docking tab, and turning off the Project Explorer and Object browser selections.

Figure 2.1: This Project window reveals that Project1 contains a forms folder that is limited to a single form.

Figure 2.1 illustrates a Project window that contains three small icons on the left-hand side.  The leftmost icon enables you to view code, while the middle one enables you to view the underlying object (which in this case is the form).  Forms, the third icon, is important when projects become large and contain several forms or when projects are combined.  With large projects, all forms are placed in one folder, and all modules are placed in a second.  Toggling forms enables you to show or hide all forms for a project that are contained in the Forms folder.

Share:

Writing and Running first Visual Basic Program

Last week you have learned how to run a program that had been made for you.  You probably noticed that when working with Visual Basic, several types of windows could be inspected – even though you were not asked to examine any one window in detail.  Here, you learn about three types of windows:

  • Project window
  • Properties window
  • Code window

You will learn how to move from one window to the next in writing a Visual Basic program.  Also, you will write and run several simple Visual Basic programs.

In working through the next few exercises you will master a number of new tasks, including how to

  • open a new project;
  • save a project;
  • name a form and project;
  • remove a form from a project;
  • add a form to a project;
  • print a form, form text, and code;
  • write a click() procedure;
  • write a KeyPress() procedure;
  • change font size, style and type;
  • change the window state.

Objectives

The tasks for this chapter are distilled into five objectives that teach you the fundamentals of writing and running a Visual Basic program, as follows:

  1. Understanding the concept of a Visual Basic project
  2. Learning how to manage Visual Basic projects
  3. Opening the Properties window and changing form properties
  4. Opening the Code window and writing Visual Basic instructions
  5. Producing a compiled application from a Standard EXE project

Understanding the Concept of a Visual Basic Project

Every Visual Basic application is defined and saved as a project.  Each project, in turn, consists of a collection of files.  These files can include modules, insertable objects, and a single resource file.  Projects themselves are tracked by a project file, which has a .VBP extension.

Form modules, as discussed earlier are first seen as windows with a caption, but Form modules contain coded instructions called procedures for the form itself and for the controls and insertable objects placed on the form.  Other modules include standard modules and class modules.  You will learn the differences among these types of modules as you progress.

The tools of the toolbox represent controls and inserteable objects.  The toolbox can be made visible or invisible by choosing View, Toolbox.  When visible, the toolbox contains a set of icons – each representing a standard or a custom control.  A visual Basic project always includes a set of standard controls and can also include custom controls.  Each custom control has an .OCX extension.  You will be asked to write some beginning Visual Basic procedures for forms.  In “Adding Controls and Event Procedures to Form MOdules, you will add procedures for standard controls.

Projects can also include a resource file, which can contain either binary data, such as images and sounds, or string data.  Resource files need to be created by a Windows resource compiler (typically a C or C++ language compiler), or you can use the resource compiler bundled with Visual Basic.

Share:

Running Visual Basic Applications

Now that you are a bit more familiar with the Visual Basic design environment, let us run few Visual Basic Applications.

Exercise 1.3  Running the Finance Calculator Demo

  1. Create a Folder with the name Finance on your Hard Drive. Copy the Finance Project Source Code, Paste them into Notepad and save them into the Finance folder with the Filename and extension specified:

    Project File: Finance.vbp

    Type=Exe
    Form=Form1.frm
    Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\WINDOWS\system32\stdole2.tlb#OLE Automation
    IconForm="Form1"
    Startup="Form1"
    Command32=""
    Name="Project1"
    HelpContextID="0"
    CompatibleMode="0"
    MajorVer=1
    MinorVer=0
    RevisionVer=0
    AutoIncrementVer=0
    ServerSupportFiles=0
    VersionCompanyName="Home"
    CompilationType=0
    OptimizationType=0
    FavorPentiumPro(tm)=0
    CodeViewDebugInfo=0
    NoAliasing=0
    BoundsCheck=0
    OverflowCheck=0
    FlPointCheck=0
    FDIVCheck=0
    UnroundedFP=0
    StartMode=0
    Unattended=0
    ThreadPerObject=0
    MaxNumberOfThreads=1
    
    [MS Transaction Server]
    AutoRefresh=1
    

    Project File: Finance.vbw

    Form1 = 138, 622, 585, 947, C, 0, 0, 0, 0, 
    

    Project File: Form1.frm

    VERSION 5.00
    Begin VB.Form Form1 
       Caption         =   "New House Payment"
       ClientHeight    =   4665
       ClientLeft      =   5565
       ClientTop       =   2115
       ClientWidth     =   6315
       LinkTopic       =   "Form1"
       ScaleHeight     =   4665
       ScaleWidth      =   6315
       Begin VB.CommandButton cmdCompute 
          Caption         =   "Compute it"
          Height          =   495
          Left            =   1440
          TabIndex        =   3
          Top             =   3840
          Width           =   2175
       End
       Begin VB.TextBox txtYears 
          Height          =   495
          Left            =   3480
          TabIndex        =   2
          Top             =   1800
          Width           =   1815
       End
       Begin VB.TextBox txtRate 
          Height          =   495
          Left            =   3480
          TabIndex        =   1
          Top             =   960
          Width           =   1815
       End
       Begin VB.TextBox txtBorrow 
          Height          =   495
          Left            =   3480
          TabIndex        =   0
          Top             =   240
          Width           =   1815
       End
       Begin VB.Label Label4 
          Caption         =   "Monthly Payments"
          Height          =   495
          Left            =   480
          TabIndex        =   8
          Top             =   2640
          Width           =   2655
       End
       Begin VB.Label Label3 
          Caption         =   "Life of Loan (in years)"
          Height          =   495
          Left            =   480
          TabIndex        =   7
          Top             =   1800
          Width           =   2655
       End
       Begin VB.Label Label2 
          Caption         =   "Yearly interest rate (i.e. 6.5)"
          Height          =   495
          Left            =   480
          TabIndex        =   6
          Top             =   960
          Width           =   2655
       End
       Begin VB.Label Label1 
          Caption         =   "Borrow"
          Height          =   495
          Left            =   480
          TabIndex        =   5
          Top             =   240
          Width           =   2655
       End
       Begin VB.Label lblPayment 
          BorderStyle     =   1  'Fixed Single
          Height          =   495
          Left            =   3480
          TabIndex        =   4
          Top             =   2640
          Width           =   1815
       End
    End
    Attribute VB_Name = "Form1"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = False
    Attribute VB_PredeclaredId = True
    Attribute VB_Exposed = False
    Private Sub cmdCompute_Click()
    Dim yearIRate As Single
    Dim nperiod As Integer
    Dim borrow As Currency
    Dim payment As Currency
    
    yearIRate = CSng(txtRate.Text) / (12 * 100)
    nperiod = CInt(txtYears.Text) * 12
    borrow = CCur(txtBorrow.Text)
    
    payment = Pmt(yearIRate, nperiod, -borrow, 0, 0)
    lblPayment.Caption = Format(payment, "Currency")
    
    End Sub
    
  2. Start Visual Basic from Windows.
  3. Select Open Project from File Menu. If a dialog box appears asking you to save a file, click No.
  4. Browse to the Finance folder, where you have saved Finance Project files and select Finance.vbp File and click the Open button.
  5. Choose Run, Start from the Visual Basic menu, or press F5. This runs the Visual Basic application.
  6. Enter Value 100,000 into the Text Control with the label borrow
  7. Enter Value 7.5 into the Text control with the label Yearly Interest Rate.
  8. Enter Value 30 into the Text control with the label Life of loan.
  9. Click on the Command Button to Calculate and display the Monthly Payments.
  10. Choose Options, Exit to exit the application and return to the Visual Basic design environment.
  11. Choose File, Remove Project to remove the Project from the design environment.

Exercise 1.4  Running the Highest and Lowest Score Values Demo

  1. Create a Folder with the name Score on your Hard Drive. Copy the Score Project Source Code, Paste them into Notepad and save them into the Score folder with the Filename and extension specified:

    Project File: HighLow.vbp

    Type=Exe
    Form=Form1.frm
    Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\WINDOWS\system32\stdole2.tlb#OLE Automation
    IconForm="Form1"
    Startup="Form1"
    Command32=""
    Name="Project1"
    HelpContextID="0"
    CompatibleMode="0"
    MajorVer=1
    MinorVer=0
    RevisionVer=0
    AutoIncrementVer=0
    ServerSupportFiles=0
    VersionCompanyName="Home"
    CompilationType=0
    OptimizationType=0
    FavorPentiumPro(tm)=0
    CodeViewDebugInfo=0
    NoAliasing=0
    BoundsCheck=0
    OverflowCheck=0
    FlPointCheck=0
    FDIVCheck=0
    UnroundedFP=0
    StartMode=0
    Unattended=0
    ThreadPerObject=0
    MaxNumberOfThreads=1
    
    [MS Transaction Server]
    AutoRefresh=1
    
    

    Project File: HighLow.vbw

    Form1 = 648, 202, 1253, 947, I, 0, 0, 0, 0, 
    

    Project File: Form1.frm

    VERSION 5.00
    Begin VB.Form Form1 
       Caption         =   "Get Score"
       ClientHeight    =   3765
       ClientLeft      =   5385
       ClientTop       =   2310
       ClientWidth     =   7785
       LinkTopic       =   "Form1"
       ScaleHeight     =   3765
       ScaleWidth      =   7785
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   1
          Left            =   1080
          TabIndex        =   0
          Top             =   240
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   2
          Left            =   2400
          TabIndex        =   1
          Top             =   240
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   3
          Left            =   3720
          TabIndex        =   2
          Top             =   240
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   4
          Left            =   5040
          TabIndex        =   3
          Top             =   240
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   5
          Left            =   6360
          TabIndex        =   4
          Top             =   240
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   14
          Left            =   5040
          TabIndex        =   13
          Top             =   1440
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   13
          Left            =   3720
          TabIndex        =   12
          Top             =   1440
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   12
          Left            =   2400
          TabIndex        =   11
          Top             =   1440
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   11
          Left            =   1080
          TabIndex        =   10
          Top             =   1440
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   10
          Left            =   6360
          TabIndex        =   9
          Top             =   840
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   9
          Left            =   5040
          TabIndex        =   8
          Top             =   840
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   8
          Left            =   3720
          TabIndex        =   7
          Top             =   840
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   7
          Left            =   2400
          TabIndex        =   6
          Top             =   840
          Width           =   1215
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   6
          Left            =   1080
          TabIndex        =   5
          Top             =   840
          Width           =   1215
       End
       Begin VB.CommandButton cmdScores 
          Caption         =   "Set High and Low Scores"
          Height          =   495
          Left            =   600
          TabIndex        =   15
          Top             =   2880
          Width           =   2655
       End
       Begin VB.TextBox txtScore 
          Height          =   495
          Index           =   0
          Left            =   6360
          TabIndex        =   14
          Top             =   1440
          Width           =   1215
       End
       Begin VB.Label Label5 
          Caption         =   "Team 3"
          Height          =   495
          Left            =   120
          TabIndex        =   22
          Top             =   1440
          Width           =   855
       End
       Begin VB.Label Label4 
          Caption         =   "Team 1"
          Height          =   495
          Left            =   120
          TabIndex        =   21
          Top             =   240
          Width           =   855
       End
       Begin VB.Label Label3 
          Caption         =   "Team 2"
          Height          =   495
          Left            =   120
          TabIndex        =   20
          Top             =   840
          Width           =   855
       End
       Begin VB.Label lblLow 
          BorderStyle     =   1  'Fixed Single
          Height          =   495
          Left            =   5640
          TabIndex        =   19
          Top             =   2880
          Width           =   1935
       End
       Begin VB.Label lblHigh 
          BorderStyle     =   1  'Fixed Single
          Height          =   495
          Left            =   5640
          TabIndex        =   18
          Top             =   2280
          Width           =   1935
       End
       Begin VB.Label Label2 
          Caption         =   "Low Score is"
          Height          =   495
          Left            =   3600
          TabIndex        =   17
          Top             =   3000
          Width           =   1815
       End
       Begin VB.Label Label1 
          Caption         =   "High Score is"
          Height          =   495
          Left            =   3600
          TabIndex        =   16
          Top             =   2400
          Width           =   1815
       End
    End
    Attribute VB_Name = "Form1"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = False
    Attribute VB_PredeclaredId = True
    Attribute VB_Exposed = False
    Private Sub cmdScores_Click()
    Static score(0 To 14) As Integer
    Dim num As Integer
    Dim High As Integer
    Dim Low As Integer
    For num = 0 To 14
      score(num) = Val(txtScore(num).Text)
    Next num
       High = High_Score(score(), num - 1)
       lblHigh.Caption = Str$(High)
       Low = Low_Score(score(), num - 1)
       lblLow.Caption = Str$(Low)
    End Sub
    
    Private Function High_Score(score() As Integer, num As Integer)
    Dim max As Integer
    Dim High As Integer
    High = 0
    For max = 0 To num
       If (score(max) > High) Then
           High = score(max)
       End If
    Next max
    High_Score = High
      
    End Function
    
    Private Function Low_Score(score() As Integer, num As Integer)
    Dim min As Integer
    Dim Low As Integer
    Low = 1000
    For min = 0 To num
       If (score(min) < Low) Then
           Low = score(min)
       End If
    Next min
    Low_Score = Low
      
    End Function
    
    
  2. Start Visual Basic from Windows.
  3. Select Open Project from File Menu. If a dialog box appears asking you to save a file, click No.
  4. Browse to the Score folder, where you have saved the Score Project files, and select HighLow.vbp File and click the Open button.
  5. Choose Run, Start from the Visual Basic menu, or press F5. This runs the Visual Basic application.
  6. Enter some random numbers into the 15 Text Boxes given with the labels Team 1, Team 2 and Team 3.
  7. Click on the Command Button to find the Highest and Lowest score values and display them.
  8. Choose Options, Exit to exit the application and return to the Visual Basic design environment.
  9. Choose File, Remove Project to remove the Project from the design environment.

Exercise 1.5  Running the Race Pace Demo

  1. Create a Folder with the name Race on your Hard Drive. Copy the Race Project Source Code, Paste them into Notepad and save them into the Score folder with the Filename and extension specified:

    Project File: Race.vbp

    Type=Exe
    Form=..\Highlow\Race\Form1.frm
    Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\WINDOWS\system32\stdole2.tlb#OLE Automation
    Startup="Form1"
    Command32=""
    Name="Project1"
    HelpContextID="0"
    CompatibleMode="0"
    MajorVer=1
    MinorVer=0
    RevisionVer=0
    AutoIncrementVer=0
    ServerSupportFiles=0
    VersionCompanyName="Home"
    CompilationType=0
    OptimizationType=0
    FavorPentiumPro(tm)=0
    CodeViewDebugInfo=0
    NoAliasing=0
    BoundsCheck=0
    OverflowCheck=0
    FlPointCheck=0
    FDIVCheck=0
    UnroundedFP=0
    StartMode=0
    Unattended=0
    ThreadPerObject=0
    MaxNumberOfThreads=1
    
    [MS Transaction Server]
    AutoRefresh=1
    
    

    Project File: Race.vbw

    Form1 = 136, 117, 583, 940, , 0, 0, 0, 0, 
    

    Project File: Form1.frm

    VERSION 5.00
    Begin VB.Form Form1 
       Caption         =   "Convert Race Result"
       ClientHeight    =   4155
       ClientLeft      =   2040
       ClientTop       =   1890
       ClientWidth     =   6585
       LinkTopic       =   "Form1"
       ScaleHeight     =   4155
       ScaleWidth      =   6585
       Begin VB.CommandButton cmdClear 
          Caption         =   "Clear"
          Height          =   495
          Left            =   840
          TabIndex        =   7
          Top             =   3240
          Width           =   1575
       End
       Begin VB.TextBox txtTime 
          Height          =   495
          Left            =   4680
          TabIndex        =   3
          Top             =   720
          Width           =   1575
       End
       Begin VB.Frame Frame1 
          Caption         =   "Click on one"
          Height          =   2175
          Left            =   480
          TabIndex        =   0
          Top             =   600
          Width           =   2415
          Begin VB.OptionButton Opt8K 
             Caption         =   "8 K Run/Walk"
             Height          =   255
             Left            =   360
             TabIndex        =   2
             Top             =   1440
             Width           =   1815
          End
          Begin VB.OptionButton Opt10K 
             Caption         =   "10 K Run/Walk"
             Height          =   255
             Left            =   360
             TabIndex        =   1
             Top             =   720
             Width           =   1815
          End
       End
       Begin VB.Label Label3 
          Caption         =   "Pace [in minutes per mile]"
          Height          =   855
          Left            =   3000
          TabIndex        =   6
          Top             =   1800
          Width           =   1335
       End
       Begin VB.Label lblPace 
          Height          =   495
          Left            =   4680
          TabIndex        =   5
          Top             =   1920
          Width           =   1575
       End
       Begin VB.Label Label1 
          Caption         =   "Enter Time in Minutes [i.e. 50.5] and press Enter"
          Height          =   855
          Left            =   3000
          TabIndex        =   4
          Top             =   720
          Width           =   1335
       End
    End
    Attribute VB_Name = "Form1"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = False
    Attribute VB_PredeclaredId = True
    Attribute VB_Exposed = False
    
    
    Private Sub cmdClear_Click()
       lblPace.Caption = ""
       txtTime.Text = ""
       txtTime.SetFocus
    End Sub
    
    Private Sub txtTime_KeyPress(KeyAscii As Integer)
    Dim result As Single
    Dim newtime As Single
    
       If KeyAscii = vbKeyReturn Then
          newtime = CSng(txtTime.Text)
          result = mph(newtime)
          lblPace.Caption = Str$(result)
       Else
          Exit Sub
       End If
    
    End Sub
    
    
    Function mph(newtime As Single) As Single
       If (Opt10K = True And newtime > 0) Then
          mph = CSng(newtime / 6.2)
       ElseIf (Opt8K = True And newtime > 0) Then
          mph = CSng(newtime / 5.1)
       End If
       txtTime.SetFocus
    
    End Function
    
  2. Start Visual Basic from Windows.
  3. Select Open Project from File Menu. If a dialog box appears asking you to save a file, click No.
  4. Browse to the Race folder, where you have saved the Race Project Files and select Race.vbp File and click Open button.
  5. Choose Run, Start from the Visual Basic menu, or press F5. This runs the Visual Basic application.
  6. Click on one of the Option Buttons to select it.
  7. Enter the value 48.45 into the Text Box.
  8. Press Enter key to calculate the pace of race in miles required per minute and display it in the label below the Text Box.
  9. Click on the Command Button to clear the values and try it on a different set of values
  10. Choose Options, Exit to exit the application and return to the Visual Basic design environment.
  11. Choose File, Remove Project to remove the Project from the design environment.

We will learn how to design these Forms and programs at a later stage.

Technorati Tags: ,,
Share:

Popular Posts

Search This Blog

Powered by Blogger.

Featured Post

Coded Statements and Methods

In the preceding procedure , you wrote several coded instructions, which introduced two different programming statements and a method: the D...

Recent Posts