Platinum Edition Using Visual Basic 5

Previous chapterNext chapterContents


- 5 -
Adding Menus and Toolbars to Your Program

In this chapter, you learn how to create a menu system for your programs like the menus you would find in most Windows programs.
You see how you can hide or disable menu items to allow the user to access them only when appropriate.
Many programs have context-sensitive menus that are displayed with a click of the right mouse button on a particular object. You learn how to add these to your programs.
Many Windows programs have one or more toolbars that provide the user quick access to the most commonly used menu commands. You see how the Toolbar control makes this easy to do.

In Chapter 4, "Working with Forms and Controls," you learned the basics of creating programs by using the forms and controls that are provided with Visual Basic. You learned how controls such as the Label and TextBox controls are used to display and sometimes edit information. You also learned how a command button can be used to let the user initiate an action. All these controls are very powerful tools, and you can create a number of applications by using just these standard forms and controls. However, there are other tools available in Visual Basic that can make your programs even more powerful and easier to use.

For example, consider a program menu. Although it's true that a menu item provides the same functionality as a command button (a way for a user to start an action), menus are much better suited for handling large numbers of possible actions. The word processor I'm using has about a hundred menu options. Can you imagine how the program would look if it used only command buttons? There would be no room left to enter text! Fortunately, the possible actions have been arranged as choices in an organized menu system. Even better, the commands I use most often are easily accessible through one of several toolbars that I can choose to display.


NOTE: In this chapter, you'll learn how you can create a sophisticated menu system for your applications. Menus in Visual Basic programs can consist of a few simple commands, or an entire repertoire of possible actions. In addition, you'll learn how to add toolbars to your programs so your users can have quick access to commonly used program functions.

Controlling a Program with a Menu Bar

One of the most important things in any program is providing the user with easy access to all of the program's functions. Users are accustomed to accessing most functions with a mouse click or two. And users want all the functions located conveniently in one place. You handle this in your programs by using menus. Visual Basic lets you quickly and easily create menus with the Menu Editor. With this editor, you create menu bars located at the top of a form, or pop-up menus that the user typically accesses by clicking the right mouse button. The menu bar from a membership program is shown in Figure 5.1.

FIG. 5.1
A menu provides a convenient location for a large number of functions.

Creating a Menu Bar

The first step in creating a menu is determining what functions need to be on the menu and how these functions will be organized. Figure 5.2 shows Visual Basic's own main menu. As you can see, the functions are organized into groups of similar items (File, Edit, View, and so forth).

Common Menus When you create your menu, you should group similar items. In fact, if possible, use groups with which your users are already familiar. This way, users have some idea where to find particular menu items, even if they've never used your program. The following list describes some standard items you will find on many menus:

FIG. 5.2
Visual Basic's main menu, shown here with its File menu opened, provides a convenient and intuitive way for users to select the various program functions.

You can use these six menus as a basis for creating your own menu system. Include any or all of them as needed by your program. If you need to add other menu groups, feel free; you are not bound to use only these options. Plan well before adding a lot of new groups. Remember that your users are probably already familiar with these types of menus, so don't confuse them by going menu-happy.

Setting Up the Main Items After deciding what functions to include in your menu and how these functions will be grouped, you can build the menu. To create a menu, first open the form where you want the menu located, and then start the Menu Editor in any of three ways: click the Menu Editor button on the toolbar, choose Tools, Menu Editor, or press Ctrl+E. The Menu Editor appears, as shown in Figure 5.3.

FIG. 5.3
The Menu Editor provides an easy way to create menus for your program.

Each line of text (menu item) in a menu is considered a Menu control. You can use the Menu Editor to create Menu controls, and to set these properties for each control:

After entering the information for one menu item, click the Next button (or press the Enter key--Next is the default button). Visual Basic then accepts the property values for the item and places it in the selection area indicated in Figure 5.3. Pressing Enter also clears the property edit areas and sets them up to accept the next item. When you're finished entering items, accept the menu by clicking the OK button on the Menu Editor. Your menu appears on the form, as shown in Figure 5.4.

FIG. 5.4
This menu bar, shown at design time, was created with the Menu Editor.


TROUBLESHOOTING: When I start to exit the Menu Editor, I get the message, Menu control must have a name. You inadvertently left out a value for the Name property of one of your menu items. Each item in a menu must have a name, even if it is just a placeholder. Fortunately, Visual Basic helps you track down your mistake by highlighting the offending item. Just enter a name for the item and continue working.

After I exited the Menu Editor, I tried to click some of the menu items to see how the menu looks, and a code window appeared. Clicking menu items at design time brings up a code window that you can use to define Click event procedures for the various menu items. This is the equivalent of double-clicking the form or another control at design time. We'll learn about writing event procedures for menu items in the section "Code for the Menu Items" a little later in this chapter. For now, just click the Close button at the code window's upper-right corner.


Multiple-Level Menus If you entered several items in the Menu Editor and clicked OK, you probably noticed that you created a series of items on only the main menu bar itself. You have no items appearing below the main items. This might be acceptable for a very simple menu, but if you place items only on the menu bar, you quickly run out of space. Obviously, you need to use multiple menu levels to handle a large number of items. The first level of a menu is the drop-down list of items appearing when you click an item on the menu bar. This is illustrated for the File menu in Figure 5.5.

FIG. 5.5
Multiple menu levels help organize your program's functions.

It is easy to create the items in different levels of a menu. You simply add the items to the menu and indent them in the Menu Editor. To indent an item, select the item in the selection area of the Menu Editor and then click the right-pointing arrow above the selection area. This indents the item one level and indicates to Visual Basic that the item is part of a submenu for the main item above it. Figure 5.6 shows the Menu Editor as it appears for the menu shown in Figure 5.5.

FIG. 5.6
The Menu Editor makes it easy to organize your program's menu system into functional groups.


NOTE: When you create multiple menu levels, Visual Basic automatically provides the arrow-like indicator that lets users know a submenu exists. Any other text in the menu item is part of the Caption property that you must enter.

If you are entering new items, each one is automatically indented to the same level as the item directly above it in the selection list. To promote an item up to a higher menu level, click the left arrow button. This promotes the item one level.


TIP: nstead of clicking the arrow buttons, you can press Alt+R to indent a menu item or Alt+L to promote an item.


NOTE: Visual Basic allows menus to have up to six levels. Usually, however, you should limit your program's menus to two or three levels. If you use too many levels, navigating the menu system tends to seem like more trouble than it's worth.

In addition to using menu levels to organize the items in your menu, you might want to further separate items in a particular level. Placing separator bars in the menu breaks up a long list of items and further groups the items, without your having to create a separate level (refer to Figure 5.6). To place a separator bar in your menu, enter a hyphen (-) in the menu item's Caption property. This causes a bar to be placed in the menu. The bar will be the full width of the drop-down menu in which it appears. Remember, you must give the separator bar a unique value for the Name property, just as with any other menu item.


CAUTION: You cannot use a separator bar in the top level of the menu (the menu bar); separator bars must be part of a submenu. If you attempt to use a separator in the menu bar, Visual Basic informs you of the error as you try to save the menu.

Modifying the Menu After creating your menu, you will probably find that you need to make some changes to the menu's structure. This also is easily accomplished with the Menu Editor. Table 5.1 lists some common editing needs and how they are accomplished.

Table 5.1 Editing a Menu with a Few Mouse Clicks

Editing Function How to Do It
Move an item Select the item and then click one of the Move arrows to move the item up or down in the list. The indentation level of the menu does not change as you move the item.
Add an item to the middle of the list Select the item that should appear below the new item in the list and then click the Insert button. A blank item appears; you can then enter the Caption and Name properties for the item. The new item is indented at the same level as the item below it.
Remove an item Select the item and then click the Delete button. The item is immediately deleted, without any confirmation. (There is no Undo feature in the Menu Editor; whatever you delete is gone.)


TIP: When moving menu items, you can use the Alt+U key combination instead of the Up button, or you can use the Alt+B keys instead of the Down button.

Adding Access Keys and Shortcut Keys for Quick Access If you have been working in Windows for a while, you have probably noticed that many menu items can be accessed by using a combination of keystrokes. You can let users access your menu items in the same way. There are two types of key combinations that can be used this way: access keys and shortcut keys. What is the access key for a menu item? The access key (sometimes called a mnemonic key) is indicated by an underscore beneath the letter in the item's caption (for example, the F in File). You create an access key by placing an ampersand (&) in front of the appropriate letter in the Caption property. For the File menu, the Caption property would be &File. You can create an access key for any or all of the items in your menu.


NOTE: While it is typical to use the first letter of the caption as the access key, this is not a good idea if that letter is already in use. For example, Visual Basic's Format menu uses the second letter as the access key to avoid conflict with the File menu. It is possible to assign the same access key to multiple menu items. If you do that, Visual Basic just cycles through the items with each press of the access key. However, this is not standard practice because having to press an access key multiple times defeats its purpose. In addition, many users don't know that they can cycle through the items in this manner, and become frustrated when they see no apparent way to select the desired choice.

When you have access keys defined for your menu, the user can select a top-level menu item (the ones in the menu bar) by holding down the Alt key and then pressing the access key. This causes the submenu for that item to drop down, showing the items for that group. The user can then start the desired task by pressing the access key defined for the menu item. For example, for the New item of the File menu, the user could press Alt+F and then press N.


NOTE: Instead of holding down Alt and pressing an access key, you can just press Alt (or F10) first, and then use the arrow keys to navigate the menus.

To create an effective set of access keys, you must specify a different key for each of the top-level menu items. Then specify a different key for each of the items in the submenu. Conceivably, you can have up to 36 access keys, one for each letter of the alphabet and one for each of the ten digits, but you will run out of screen space for the choices before running out of letters.


TIP: If possible, use the first letter of the menu item as the access key, because typically the user expects this.

In addition to the access keys just discussed, you can assign shortcut keys to some of the more commonly used functions in your program. Shortcut keys provide direct access to a function through a single key (such as Delete) or key combination (such as Ctrl+S), without having to navigate the menu system. Users can take advantage of shortcut keys to perform tasks quickly.

To assign a shortcut key to one of your functions, enter the Menu Editor, select the menu item for which you want a shortcut key, and then select the desired key from the Shortcut list. The key is assigned to that function, and the shortcut-key information appears next to the menu item in the menu (see Figure 5.7). There are 79 shortcut keys that you can use.

FIG. 5.7
Ctrl+O has been assigned as the shortcut key for the File, Open menu function.

You can assign any unused shortcut key to any menu item, but be aware that there are a few "standard" keys used in many Windows programs. Some of these keys are listed in Table 5.2. As examples, the "Description" column explains what these keys do when you're working within Visual Basic itself.

Table 5.2 Shortcut Keys Speed Access to Program Tasks

Menu Item Shortcut Key Description
Edit, Cut Ctrl+X Removes selected text or control(s) from its current location and copies it to the Clipboard.
Edit, Copy Ctrl+C Makes a copy of the selected text or control(s) in the Clipboard.
Edit, Paste Ctrl+V Pastes the contents of the Clipboard to the active form or Code window.
Edit, Undo Ctrl+Z Undoes the last change.
Edit, Find Ctrl+F Opens the Find dialog box to allow the user to search for text.
File, New Ctrl+N Creates a new Visual Basic project.
File, Open Ctrl+O Opens the Open Project dialog box to allow the user to select a project to open.
File, Save Ctrl+S Saves the current file.
File, Print Ctrl+P Opens the Print dialog box to allow selection of items to be printed.


TIP: As with access keys, try to have the shortcut key correspond to the first letter of the item name; for example, Ctrl+P for Print. This makes it easier for users to remember the shortcuts. To avoid confusing your users, use the standard shortcut keys listed in Table 5.2 whenever possible.


TROUBLESHOOTING: When I try to save the changes to my menu, I get the error message Shortcut key already defined. What happened? If you got this message, you inadvertently gave the same shortcut key to two or more functions. You need to look through the menu-item selection area to find the duplicate definition, and then assign another key to one of your items.

Code for the Menu Items

After creating the menu's structure, you need to write code to let the menu items actually perform tasks. As with a form or other controls, you do this by writing code in an event procedure. A menu item handles only one event--the Click event. This event is triggered when the user clicks the menu item, or when he selects the item and presses Enter.


NOTE: A menu item's Click event is also triggered when the user uses an access key or shortcut key to access an item.

To add code to a menu item's Click event, first select the menu item on the form by clicking the item. This starts the Code Editor and sets up the Event procedure for the selected item. Then simply type in the code to handle the task. The following sample code could be used to create a new database in response to a menu selection:

Private Sub mnuNewDb_Click()
  Dim sFileName As String
  dlgGetFile.ShowOpen
  sFileName = dlgGetFile.FileName
  Set dbMain = DBEngine.WorkSpaces(0).CreateDatabase(sFileName,dbLangGeneral)
  MsgBox "New database created."
End Sub

The preceding code uses a CommonDialog control named dlgGetFile to obtain a file name from the user. It then uses this file name to create a new database.

See "Using Built-In Dialog Boxes," Chapter 6

Optional Settings

In addition to the required Caption and Name properties, each menu item has several optional properties that you can set either to control the behavior of the menu or to indicate the status of a program option. Three of these properties are Visible, Enabled, and Checked. The menu item's Visible and Enabled properties work just like their counterparts on a form or control. When the Visible property is set to True, the menu item is visible to the user. If the Visible property is set to False, the item and any associated submenus are hidden from the user. You have probably seen the Enabled and Visible properties used in a word processing program (though you might not have been aware of how it was accomplished), where only the File and Help menus are visible until a document is selected for editing. After a document is open, the other menu items are shown. Changing the setting of the Visible property allows you to control what menu items are available to the user at a given point in your program. Controlling the menu this way lets you restrict the user's access to menu items that might cause errors if certain conditions are not met. (You wouldn't want the user to access edit functions if there was nothing to edit, right?)

The Enabled property serves a function similar to that of the Visible property. The key difference is that when the Enabled property is set to False, the menu item is grayed out. This means that the menu item still can be seen by the user but cannot be accessed. For example, the standard Edit, Cut and Edit, Copy functions should not be available if there is no text or object selected, but there's nothing wrong with letting the user see that they exist (see Figure 5.8).

FIG. 5.8
Disabled menu items are visible to the user but are shown in gray tones, indicating that the items are unavailable at the present time.

Both the Visible and Enabled properties can be set in the Menu Editor at design time, and from your program code at runtime. In the Menu Editor, the properties are set by using check boxes. The default value of the properties is True. In code, you set the property value by specifying the name of the menu item (from the Name property), the name of the property, and the value you want to set. This is shown in the following line of code for the Edit menu:

Mnu_Edit.Visible = False

The Checked property of the menu item determines whether or not a check mark is displayed to the left of the item in the menu, as shown in Figure 5.9. The Checked property is typically used to indicate the status of a program item or option; for example, whether a toolbar or particular window is visible. The menu item is then used to toggle back and forth between two program states. The following code causes the menu's check mark to toggle on and off every time it is clicked:

Private Sub mnuShowSorted_Click()
  mnuShowSorted.Checked = Not(mnuShowSorted.Checked)
End Sub

Because the Checked property can only be True or False, the preceding code makes nice use of some Boolean logic with the Not() function. At any point in the program code, the state of the Checked property indicates whether or not the user wants something to be displayed in sorted order.


CAUTION: You cannot set the Checked property to True for an item on the menu bar (top menu level). Doing so results in an error.

You might have also noticed two other items in the Menu Editor. These items specify the value of the NegotiatePosition and WindowList properties of the menu item. The NegotiatePosition property specifies whether and where the menu item of your application is displayed when an embedded object on a form is active and its menu is shown (for example, if your application has an instance of Word embedded for modifying a document). If the NegotiatePosition property is 0, your menu is not displayed while the object is active. If the property is not 0, your menu item is displayed to the left of, in the middle of, or to the right of the object's menu (property settings of 1, 2, or 3, respectively).

The WindowList property specifies whether the current item will contain a list of MDI child forms that are open within the MDI parent. When this property is set to True, the menu automatically adds items as child forms are opened and removes the items when the corresponding child form is closed.

See "Maintaining a Window List," Chapter 16

Creating Pop-Up Menus

So far, the discussion of menus has looked at the menu bar that appears along the top of the form. Visual Basic also supports pop-up menus in your programs. A pop-up menu is a small menu that appears somewhere on your form in response to a program event.

Pop-up menus often are used to handle operations or options related to a specific area of the form (see Figure 5.10)--for example, a format pop-up menu for a text field that lets you change the font or font attributes of the field. You can find this menu type in many of the latest generation of Windows programs, including Visual Basic itself.

When a pop-up menu is invoked, usually with by right-clicking the mouse, it appears on-screen near the current mouse pointer location. The user then makes a selection from the menu. After the selection is processed, the menu disappears from the screen.

FIG. 5.10
This grid's pop-up menu provides a convenient way to initiate program functions specifically related to the grid.

Creating the Menu to Be Displayed

You create a pop-up menu in the same way that you created the main menu for your program--from the Menu Editor. There is, however, one extra step. The pop-up menu should be hidden, so that it does not appear on the menu bar. To do this, set the Visible property of the top-level menu item to False.


NOTE: Typically, you will hide the menu item that is used as a pop-up menu, but you can use any of the top-level items of a menu bar as a pop-up menu. That is, a particular menu can appear both as a pop-up menu and as a part of the main menu of a form.

Creating a pop-up menu is easy. The following four steps tell you how to create a pop-up menu to handle text formatting:

1. Create a top-level menu item with Format as its Caption property and popFormat as its Name property.

2. Set the Visible property of the menu item to False by clearing the Visible check box in the Menu Editor.

3. Create three submenu items under popFormat, with the Caption properties Bold, Italic, and Underline and the Name properties popBold, popItalic, and popUnder, respectively.

4. Click the OK button to accept the menu changes.

Notice that the Format menu does not appear on your form's menu bar. However, the menu is present and can be modified in the Menu Editor.

The technique you must use to add code to the Click event of the items in a pop-up menu is also a little different. Because the menu is not visible on the form, you cannot just click the item to bring up the code-editing window. Instead, bring up the code-editing window by selecting the View Code button in the Project window, or double-clicking the form. Then, select the desired menu item in the Code window's Object list at the upper-left corner. This enables you to enter code for the hidden items.

Activating a Pop-Up Menu

To have the pop-up menu appear on your screen, you must invoke the form's PopUpMenu method. You do this by specifying the name of the form where the menu will be displayed, the PopUpMenu method, and the name of the menu to be shown.

While you can use this method from anywhere in your code, pop-up menus are used most often in response to mouse clicks, usually those using the right mouse button. The following code shows how the Format menu created in the last section would be called up by clicking the right mouse button anywhere on your form:

Private Sub Form_MouseUp(Button As Integer, Shift As Integer,  X As Single, Y As Single)
  If Button = vbRightButton Then
     frmMain.PopUpMenu popFormat
  End If
End Sub

In this code segment, the MouseUp event is used to take an action whenever a mouse button is pressed. The event passes a parameter, the Button parameter, that tells you which of the mouse buttons was pressed. Because you want the menu to appear in response to only a right button click, you check for the value of the Button parameter. If it is equal to vbRightButton (an intrinsic constant for the right mouse button), the pop-up menu is displayed.


NOTE: You can create multiple pop-up menus and have them displayed in response to different mouse buttons or in different areas of the screen. The X and Y parameters passed in to the MouseUp event procedure report the location of the mouse cursor at the time the event occurred.

Creating a Toolbar for Your Application

You have probably noticed that many Windows programs now have one or more toolbars in addition to the menu. These toolbars provide the user with an easy way to access the most commonly used functions of the program. Some programs also use toolbars to help with specific tasks, such as the Drawing toolbar that is in Microsoft Word. Because toolbars are becoming so common, users have come to expect to find them in all programs.

Fortunately, it is easy for you to set up a toolbar in Visual Basic. To create a toolbar, you only need to use two controls--the Toolbar control and the ImageList control. The Toolbar control sets up the buttons of the actual toolbar displayed to the user and handles the user's actions. The ImageList control contains a collection of bitmaps for use by other controls. In this case, our Toolbar control will display images from the ImageList on its buttons.

Setting Up the Toolbar Control

To set up a toolbar on your form, you eed to add the Toolbar and ImageList controls to the Toolbox. These two controls are part of the Windows Common Controls group. This group of controls is included with VB, but is not in the Toolbox by default. To add them to the Toolbox, use the Components dialog box, which you access by selecting Project, Components; then select the check box for Microsoft Windows Common Controls 5.0.

Getting the Images for Your Toolbar After these controls have been added to the Toolbox, you can begin the creation of your toolbar. Follow these steps to create a toolbar:

1. Draw an ImageList control on your form and give it a unique name. Because the ImageList control is not visible to the user, its size is set by Visual Basic. No matter what size you draw it on the form, it always appears as a little box.

2. To add bitmap images to the control, open its Property Pages dialog box by either pressing the ellipsis (...) button of the Custom property in the Properties window, or by right-clicking the ImageList control and selecting Properties. From this dialog box, shown in Figure 5.11, you can add images from graphics files (icons and bitmaps) stored on your hard drive.

FIG. 5.11
At design time, adding images to the ImageList control is accomplished with the Images page of the Property Pages dialog box.

3. To add an image to the ImageList control, click the Insert Picture button. This presents you with the Select Picture dialog box, from which you can choose the bitmap or icon you want. As you select the picture, it is added to the control and displayed in the Images area.

4.
When you have added all the pictures you might need, click the OK button to close the dialog box.

After completing these steps, your ImageList control will be ready to use for supplying images to your toolbar.

Creating the Toolbar Next, you need to set up the toolbar itself by following these steps:

1. Select the toolbar icon in the Toolbox, and draw the Toolbar control on your form. Visual Basic positions the toolbar at the top of the form, and the control spans the width of the form.

2. A toolbar can be aligned along any of the four edges of its form. If, for example, you want to position it along the bottom of your form, set its Align property to 2 - vbAlignBottom. You can align it to the left or right edge of the form by setting the Align property to 3 - vbAlignLeft or 4 - vbAlignRight, respectively; in these cases, you should adjust the Width property to keep it from filling the form completely. If you want a free-floating toolbar, set its align property to 0 - vbAlignNone; you can then adjust its position and size by setting the Left, Top, Width, and Height properties.

3. To continue setting up the Toolbar control, bring up its Property Pages dialog box by right-clicking the control and choosing Properties. Figure 5.12 shows the first page of the Toolbar control's Property Pages.

FIG. 5.12
You can assign an ImageList control to your toolbar in the General tab of the toolbar's Property Pages dialog box.

4. Next, set the Toolbar control's ImageList property to the name of the ImageList control that you already set up to provide images. Clicking the arrow to the right of the ImageList property provides you with a list of all ImageList controls on the current form.

There are several other properties on the Property Pages' General tab that control the appearance and behavior of the toolbar. These properties are summarized in Table 5.3.

Table 5.3 Toolbar Properties that Control Its Appearance and Behavior

Property Name Description
BorderStyle Determines whether a single-line border is displayed around the toolbar or no border is used.
ButtonHeight Specifies the height (in twips) of the buttons in the toolbar.
ButtonWidth Specifies the width (in twips) of the buttons in the toolbar.
AllowCustomize Determines whether the user is allowed to customize the toolbar by adding, deleting, or moving buttons.
ShowTips Determines whether ToolTips are shown if the mouse is rested on one of the buttons.
Wrappable Determines whether the toolbar wraps around to a second row of buttons if there are more buttons than fit on a single row.

Creating the Buttons of the Toolbar The next step in creating your toolbar is to create the buttons that will be placed on the toolbar. For this, you move to the Buttons page of the Property Pages (see Figure 5.13).

FIG. 5.13
You assign images, captions, and identifiers to toolbar buttons in the Buttons page.

To add a button to the toolbar, click Insert Button. This adds a new button after the current button. For each button that you add, you need to specify several properties--the Key property, the Style property, and the Image property. These three are the minimum required to set up a button.

The Key property specifies a string that is used to identify the button in code. You see how this is used in the following section, "Enabling the Buttons with Code." The Key property for each button must be unique, and you should assign a string that is meaningful to you. This makes it easier to remember when you are writing your code. The Image property specifies the index of the picture that you want to appear on the face of the button. The index corresponds to the Index of the picture in the ImageList control. You can specify a value of zero for the Image property if you do not want a picture to appear on the button.

The Style property determines the type of button that you create. Table 5.4 summarizes the various settings of the Style property. Each of the button styles is shown in Figure 5.14.

FIG. 5.14
Examples of the different toolbar button styles. Note that the placeholder and separators are not really buttons.

Table 5.4 Style Property Settings that Control the Behavior of Toolbar Buttons

Setting VB Constant Description of Behavior Example
0 tbrDefault The button is a standard pushbutton. The Save Project button in VB.
1 tbrCheck The button indicates that an option is on or off by its state. The Bold button in Word.
2 tbrButtonGroup The button is part of a group. Only one button of the group can be depressed at a time. The alignment buttons in Word.
3 tbrSeparator The button is used to provide space between other buttons. The button has a width of eight pixels. N/A
4 tbrPlaceHolder This button is used to hold a space in the toolbar for other controls such as a combo box. The font combo box in Word.

In addition to these three key properties, there are several other properties that can be set for each button on the toolbar (see Table 5.5).

Table 5.5 Optional Properties that Provide Further Control over a Button Toolbar

Property Description
Caption This is text that is displayed beneath the picture on a button.
Description This is text that describes the button to the user when he invokes the Customize Toolbar dialog box.
ToolTipText This text appears when the mouse is rested on the button. This text is only displayed if the ShowTips property of the toolbar is set to True (which is the default).
Value Sets or returns the current state of the button. A value of 0 indicates that the button is not pressed. A value of 1 indicates that the button is pressed. You typically set the value of a single button in a button group to 1. You can then use the Value property in your code to determine which button is pressed.


TIP: Unless the images on your buttons are self-explanatory, you should make sure to include ToolTips. Otherwise, there is no way for the user to know what the button does unless he presses it. ToolTips give your program a professional appearance and are easy to add.

After setting up the buttons on the toolbar, you can exit the Property Pages dialog box by clicking the OK button. Your toolbar is now set up and ready for use--almost.

Enabling the Buttons with Code

You have seen how to set up the toolbar, but until you add code to the toolbar's events, it cannot perform any functions. The buttons of the toolbar do not have events of their own. Instead, you actually write your code for the ButtonClick event of the toolbar itself. This event passes a Button object, representing the button that was pressed, as a parameter to the event procedure. In your code, you use the value of the Button object's Key property to determine which button was actually pressed. Listing 5.1 shows a typical event procedure for taking actions based on the button pressed.

Listing 5.1 TOOLBAR.FRM--Using the Key Property of the Button to Determine What Action to Take

Private Sub Toolbar1_ButtonClick(ByVal Button As ComctlLib.Button)
  Select Case Button.Key
     Case "New"
          mnuNew_Click
     Case "Open"
          mnuOpen_Click
     Case "Save"
          mnuSave_Click
  End Select
End Sub

In Listing 5.1, the procedures being called are actually the Click event procedures of menu items. This allows you to code an action once and then call it from either the menu or the toolbar. Doing this makes it easier to maintain your code because changes or corrections only have to be made in a single location. Also, note the introduction of the Select Case statement, which is more readable than a nested If statement. We'll discuss it in more detail in a later chapter.

The project TOOLBAR.VBP contains the sample program used in this chapter. The program shows a standard menu, a pop-up menu, and a toolbar.

Allowing the User to Customize the Toolbar

One of the really great features of the Toolbar control is that you can allow your users to customize the toolbar to their liking. When the AllowCustomize property of the toolbar is set to True, the user can access the Customize Toolbar dialog box by double-clicking the toolbar. This dialog box, shown in Figure 5.15, allows the user to add buttons to the toolbar, remove buttons, or move the buttons to a different location.

FIG. 5.15
The AllowCustomize property lets users customize the toolbar to their liking, without the need for additional code.

Other Methods of Creating a Toolbar

Although using the Toolbar control is the easiest method of creating a toolbar for your application, there are other ways of accomplishing the task. You can use a picture box as a container and Image controls to represent the buttons. One advantage of this method is that you can use the picture box to display other images besides the buttons. You can also use graphics methods and print methods to display other information. Another advantage is that the toolbar created with a picture box can be located anywhere on your form. You see how to create a toolbar using a picture box in Chapter 13, "Using Containers."

There are also several third-party controls that allow you to create toolbars for your forms. Some of these controls even allow you to create floating toolbars like Visual Basic's Form Editor toolbar.

From Here...

This chapter has shown you the advantages of creating menus and toolbars for your programs. Hopefully, you have also seen how easy it is to create these items. You were also exposed to several other topics in this chapter. To learn more about them, refer to the following chapters:


Previous chapterNext chapterContents


Macmillan Computer Publishing USA

© Copyright, Macmillan Computer Publishing. All rights reserved.