Visual Basic Concepts

Clicking Buttons to Perform Actions

The easiest way to allow the user to interact with an application is to provide a button to click. You can use the command button control provided by Visual Basic, or you can create your own "button" using an image control containing a graphic, such as an icon.

Using Command Buttons

Most Visual Basic applications have command buttons that allow the user to simply click them to perform actions. When the user chooses the button, it not only carries out the appropriate action, it also looks as if it's being pushed in and released. Whenever the user clicks a button, the Click event procedure is invoked. You place code in the Click event procedure to perform any action you choose.

There are many ways to choose a command button at run time:

  • Use a mouse to click the button.

  • Move the focus to the button by pressing the TAB key, and then choose the button by pressing the SPACEBAR or ENTER. (See "Understanding Focus" later in this chapter.)

  • Press an access key (ALT+ the underlined letter) for a command button.

  • Set the command button's Value property to True in code:

    cmdClose.Value = True
    
  • Invoke the command button's Click event in code:

    cmdClose_Click
    
  • If the command button is the defaultcommand button for the form, pressing ENTER chooses the button, even if you change the focus to a different control other than a command button. At design time, you specify a default command button by setting that button's Default property to True.

  • If the command button is the default Cancel button for the form, then pressing ESC chooses the button, even if you change the focus to another control. At design time, you specify a default Cancel button by setting that button's Cancel property to True.

All these actions cause Visual Basic to invoke the Click event procedure.

The Test Buttons Application

You use the Caption property to display text on the button to tell the user what the button does. In Figure 3.4, the Test Buttons example from the Controls sample application contains a command button with its Caption property set to "Change Signal." (For a working version of this example, see Button.frm in the Controls.vbp sample application.)

Notice that 'S' is the access key for this button, denoted by an underline. Inserting an ampersand (&) in the text of the Caption property makes the character following it the access key for that button (for example, Change &Signal).

Figure 3.4   Command button with a caption

When a user clicks the command button, the code in the command button's Click event procedure is executed. In the example, a different traffic light icon is displayed each time the button is clicked.

For More Information   For information on additional properties of the command button, see "Using Visual Basic's Standard Controls."