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:

Trending

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