Using Visual Basic 6

Previous chapterNext chapterContents


- 13 -
Creating Menus in Your Programs


Understanding the Windows Standard Menus

Any program with more than a few simple functions or features can benefit from the addition of a well-built menu. When you design your program, the goal is to make your features as easy to use as possible. A well-designed menu will accomplish this goal.

The menu will be one of the most visible features of your application. A good menu will make using your program easy. Your program will seem natural and familiar to the user. A bad menu at best will confuse your users and could actually keep them from understanding how your program works.

Many programs have file functions that let users create and save files. Programs that use any common Windows features, such as opening and saving files or copying and pasting text, have the additional requirement of complying with the expected standards for Window application menus. You handle this expectation of your programs by building Windows standard menus.

Microsoft's goal is to make all the main Windows features standard across the entire Windows graphical user interface (GUI). This basically means that no matter what program you are in--whether it be Word, Excel, or Access--the main features will look and work the same. For instance, the way you access the Printer feature in one program will be the same in all programs across the entire platform. These standards are documented in many places, such as in the help systems within Windows, on Microsoft's Web page, and in countless books, magazines, and articles.


When to break tradition

Unless there's a powerful reason to go against the tradition of using the File, Edit, and Help menus in your application, it's better to observe this tradition. One example of when it would be important to break with tradition is when your functions are significantly different from the standard functions. The new location alerts your users that something is different from what they would normally expect to do.


The expected location and function of the common Windows menu features have evolved through habit. The most common features are the File, Edit, and Help menus. The first two are usually the first choices on the left side of the menu bar; the Help menu is usually the last choice on the main menu bar. Don't use >> to indicate submenus.

The individual elements of Windows standard menus also follow a standard, as listed in Table 13.1.

TABLE 13.1  Windows Standard Menu Conventions

Feature Convention
Caption Use one or two short specific words.
Organization Menu items should be grouped logically by function and allow for a minimal number of levels to access each feature.
Access keys Each menu item should be assigned an access key (the underlined letter in a menu or menu selection) to allow for keyboard access to the menu choices. The key should be unique in each section of the menu and is normally the first letter of the caption.
Shortcut keys Any menu features that are frequently used or need to be available from any part of the program should be assigned a shortcut key. Each shortcut key can be assigned to only one menu item.
Check box Menu items that simply set or clear a single program option should contain a checked feature directly in the menu.
Ellipsis Each menu item that opens a dialog should be followed by an ellipsis (...).

Using Visual Basic's Application Wizard

Visual Basic 6 has improved the Application Wizard to allow for the creation of fully customized menus directly in the wizard. In the earlier versions of the wizard, you could select from only a limited set of standard menu options to include in your application. This improvement makes the wizard a useful tool and a good starting point for building and understanding your first menu.


Application Wizard options

Most programmers don't know all the standard features they want to use in an application until later in the development process. For this reason, if you use the Application Wizard, you should select any option you think you might use in your program. You can always delete it later.


The primary benefit of VB's Application Wizard is that it can make menus that have the Windows standard features already loaded. You simply select the features you want from the template provided. They're also already arranged in the Windows standard layout.


Limitations of the Application Wizard

You can't use the Application Wizard to modify existing projects. Many third-party support programs add more functionality to your project without having you do more programming. You can also use the add-ins that come with Visual Basic, such as the Menu Editor.


The Application Wizard is a straightforward tool for building a new application. This means that the Application Wizard is used to build a functional application shell with standard features. If you want additional features, you have to program them yourself or use the Menu Editor to add them. After you click Finish in the Application Wizard and the base program is generated, you're on your own to make changes to the program by using the Menu Editor (discussed later in this chapter).

Build a simple menu with the Application Wizard

1. Start the Application Wizard through the default dialog that opens when Visual Basic 6.0 starts or by choosing New Project from the File menu (see Figure 13.1).

FIGURE 13.1 Double-click the Application Wizard icon to start the wizard.

2. The wizard's Introduction dialog allows you to reuse the answers you saved during a previous Application Wizard session (see Figure 13.2). Leave the default choice and choose Next.


Save some time in building the program menu

By saving your settings in the Application Wizard, you can save time re-entering choices you've already made. The Application Wizard saves the menu and toolbar settings in a profile file (.RWP). Profiles also provide a basis for a consistent look and feel to your programs while reducing duplicate effort in building the menus. This allows for a common starting point in the development of an application, which is helpful in large projects in which many teams of developers might be working on separate parts of a single large application.


3. In the Interface Type dialog, select the type for the initial application screen (see Figure 13.3). For this sample application, select Single Document Interface. Leave the default project name and choose Next.

4. A Windows standard default menu is created for you to begin to modify. Not all possible choices have been selected in the initial menu, as shown in Figure 13.4. After you make your modifications, choose Next.

5. The Application Wizard allows for the customization of a toolbar, resource file, browser, database connectivity, and other templates. For this example, skip these dialogs; choose Next five times to get to the final dialog.

FIGURE 13.2 Profiles allow for the reloading of choices from previously completed and saved Application Wizard sessions.

FIGURE 13.3 Selection of interface types is based on how the application will be used. Multitask applications often use MDI.

FIGURE 13.4 Select the menu and submenu types for your application.

6. In the last dialog, you can save your profile (see Figure 13.5). Enter a name for your profile that will be easy to relate to your application. After you enter the name, choose Finish to complete the Application Wizard. (Clicking Finish on any of the earlier dialogs in the wizard bypasses the option to save the profile for future use.)

FIGURE 13.5 Enter the profile name on the final screen.

Using Visual Basic's Menu Editor

The Menu Editor allows you to create menu bars from scratch or modify already created menus. As with the Application Wizard, these menus are located at the top of a form, with associated drop-down submenus or pop-up menus that users typically access by right-clicking.

Make a simple menu with the Menu Editor

1. Open a new project. Save the project with a new filename. Rename the default form (with a name such as frmMenu) and save it to a new filename, such as frmMenu.frm.


Don't press Enter yet!

Press Tab or use the mouse to move between text boxes in the Menu Editor; otherwise, you cause the Menu Editor to create a new menu item.




Using ampersands

Including an ampersand in the menu caption forces the character that comes after it to be underlined when it appears in the menu. The underlined character becomes the hot key, which users can press (combined with the Alt key) to make a selection. For example, with the F underlined on the File menu, users can press Alt+F to pull down that menu.


2. Open the Menu Editor by clicking the Menu Editor button on the Standard toolbar. If the form doesn't have the focus, the Menu Editor icon is grayed out.

3. In the Menu Editor dialog, type &File in the Caption text box and mnuFile in the Name text box. Click Next.

4. Click the button with the arrow pointing to the right. This is the indent button.

5. Type E&xit in the Caption text box and itmExit in the Name text box. Your menu should appear in the dialog as shown in Figure 13.6.

6. Click OK.

7. The menu you created is embedded in the form (see Figure 13.7). Drop down the File menu that you just created and click Exit. The code window for the itmExit_Click() event procedure appears.

8. Add the Unload Me statement to the itmExit event procedure, as shown in Figure 13.8.

9. Press F5 to run the code.

FIGURE 13.6 The arrow buttons allow you to indent and rearrange items in the menu list.

FIGURE 13.7 An entry item in a menu is like any other Visual Basic control. It has properties and one event: the click event.

Granted, this exercise is simple, but it demonstrates the fundamental techniques for making a menu with the Menu Editor. You've added a File menu to the main form. Your menu has a submenu item, Exit, that allows users to terminate the program. You accomplished program termination by putting the End statement in the event procedure for the Exit menu item's click event.

FIGURE 13.8 You write code in menu-item event procedures as you would for any other Visual Basic control.

Setting Menu Properties

As mentioned earlier, a menu is a control with its own set of properties and one event, the Click() event. Table 13.2 shows the most commonly used properties for a Menu object.

TABLE 13.2  Commonly Used Properties of the Menu Object

Property Value/Type Description
Caption String The text that appears on the menu bar.
Checked Boolean Puts a check mark before the Caption string of a menu item.
Enabled Boolean Doesn't gray out the Caption string if True.
Name String The name of the object--available only at design time.
Property Value/Type Description
Shortcut N/A A key combination that allows you to access the menu item's functionality. You can choose this setting only at design time from a list that appears in the Shortcut drop-down list in the Menu Editor.
WindowList Boolean Makes a top-level menu in an MDI form display a list of windows open in that MDI form--available only at design time.

As with any control, you assign a value to the Name property when you create a menu or menu item. Failing to set the Name value results in an error. Another common mistake is to leave the value of the Caption property set to null (""), which results in a functional menu item that shows up in the menu bar as a blank line.

Adding Access Keys to Menu Items

In addition to clicking a menu item to perform a task, you can access a menu item's functionality by using access keys. Access keys allow users to perform menu selections by pressing Alt and then the assigned letter of the access key. After a menu is open, users select from the menu by pressing the access key for the desired menu choice.

An access key is denoted by an underlined character in a menu item's Caption--for example, the F in File on a standard Windows menu bar. When you press Alt+F, the result is the same as if you had clicked File on the menu bar.

To denote an access character, put an ampersand before the character you want to use. In Figure 13.9, the ampersand indicates that the letter F in File will be underlined.

FIGURE 13.9 Shortcut keys are assigned in the Menu Editor before compiling the program and can't be changed in the runtime environment.


Don't do this!

Putting two access keys with the same letter in the same part of the submenu is bad programming practice and should be avoided. Doing so just complicates things for users; however, the purpose of using GUIs is to simplify things.


Access keys are grouped according to menus. You can have different access keys with the same letter--Save and Paste Special, for instance--as long as they appear in different menus. (In Microsoft Word, these commands would appear under the menus File and Edit, respectively.) If you put two access keys with the same letter in the same part of the submenu, the first key in the hierarchy will be the first one executed. When the access key is pressed for the second time, the next menu item with the same matching key is selected.

Access keys are especially helpful in programs that require a lot of keyboard entry. If an access key is assigned, your users don't have to break their typing position and reach for the mouse to perform a function.

Adding Shortcut Keys to Menu Items


Adding shortcut keys with the Menu Editor

In the Application Wizard, you aren't given a chance to enter any shortcut keys for your custom menu items; the standard Windows menu shortcuts are added. You have to use the Menu Editor to go back in and add shortcut keys to your custom menu elements.


Using shortcut keys (also known as accelerator keys) is another way of performing menu functions from the keyboard. You set a shortcut key combination by choosing a combination from the Menu Editor's Shortcut drop-down list (see Figure 13.10).

Shortcut keys work anywhere in the program, whether or not the menu item is visible. That's why they're called shortcuts--they're active all the time, and users can jump to the function without going through the menu selection process.

FIGURE 13.10 Each application can have only one instance of an accelerator key combination. If you use Ctrl+N for New, you can't use Ctrl+N for Open too.

You can assign a shortcut key or key combination to only one menu element; redundancies aren't accepted. The Visual Basic IDE catches the error when you attempt to enter a duplicate entry (see Figure 13.11). In this situation, Visual Basic doesn't enforce uniqueness when editing menus.

FIGURE 13.11 Visual Basic's Menu Editor catches the error when you click OK.

Creating Pop-Up Menus

There are two types of menus: menu bars and pop-up menus. A menu bar is the type that you made with the wizard and edited in the Menu Editor--a sequence of menus embedded on a form. A pop-up menu is, as the name implies, a menu that pops up from somewhere on a form. When you right-click in the Windows Explorer, for example, a pop-up menu appears. You can make any menu appear as a pop-up menu by using a form's PopupMenu method:

PopupMenu mnuFile

A menu command can exist within a menu bar and as a pop-up menu, if you want (see Figure 13.12). You need to create a form to go with the pop-up menu because the PopupMenu method must be part of a form. The following code demonstrates how this feature works:

Private Sub Form_MouseDown (Button As Integer, _
  Shift As Integer, X As Single, Y As Single
   If Button = 2 Then
      PopupMenu mnuFile
   End If
End Sub

For this code to work, you need to create a form that includes a Menu control to be named mnuFile, which must have at least one submenu. You need to program this code into the form's Declarations section and press F5 to run it.

FIGURE 13.12 When you use the PopupMenu method as shown in the form on the right, only the submenu items of a menu will appear.

Creating Complex Menus

Now that you have an overview of how to use the Menu Editor to make a menu, the following example creates a menu system for a simple text editor.

The Amazing Text Editor, the code for which is in the project TextEdit.vbp on the Web site at http://www.mcp.com/info, can do the following tasks:

Before you start coding, take some time to review the program's features to make a properly designed and categorized menu system. As mentioned earlier in the section "Understanding the Windows Standard Menus," most menu bars begin with a File menu and are followed by an Edit menu.

The following is a viable menu categorization for the feature set of the Amazing Text Editor.

File Menu Edit Menu
New Undo
Open Cut
Save Copy
Settings Paste
About Select All
Exit

Now that you have a categorized menu system, you can implement it in the Menu Editor. Table 13.3 shows the menu hierarchy and Name and Caption properties, as well as accelerator and shortcut keys for each menu object.


Standard functionality of shortcut keys

The shortcut keys used in Table 13.3 adhere to the established convention that Windows programmers use for menu items with the demonstrated functionality.


TABLE 13.3  Menu Objects for the Amazing Text Editor Application

Name Caption Level Shortcut
mnuFile &File 0 None
itmNew &New 1 None
itmOpen &Open 1 None
itmSave &Save 1 None
sepOne - (a hyphen) 1 None
itmSettings Se&ttings 1 None
itmBlackOnWhite Black On White 2 None
itmWhiteOnBlack White On Black 2 None
itmAbout &About 1 None
sepTwo - 1 None
itmExit E&xit 1 Ctrl+X
mnuEdit &Edit 0 None
itmUndo &Undo 1 Ctrl+Z
sepThree - 1 None
itmCut Cu&t 1 Ctrl+X
itmCopy &Copy 1 Ctrl+C
itmPaste &Paste 1 Ctrl+V
sepFour - 1 None
itmSelectAll Select &All 1 Ctrl+A

Adding Separator Lines to Menus


Separator line limits

You can't use separator lines at the 0 (zero) level of a menu's hierarchy. You must be at least one indent level in.


You add separator lines to a menu by typing a single hyphen (-) in the Menu Editor's Caption text box. Notice that Table 13.3 lists some entries that have a Caption value of - and begin with the prefix sep in the object name. When you run the program, separator lines appear in the drop-down menus where the hyphens are used (see Figure 13.13). I use the sep prefix to denote that the name of the menu item reflects a separator line.

FIGURE 13.13 If a submenu item has another submenu associated with it, you'll see a right-pointing arrow to the right of the submenu item's caption.

Separator lines

Using the Checked Property

You use a menu's Checked property to communicate that some state exists or that a choice has been made. The Amazing Text Editor uses check marks in its menu system to communicate the current choice made for font/background color layout (refer to Figure 13.13). If users choose the Black on White menu item, a check mark will appear next to the selection, the font color will be set to black, and the background client area will be set to white.

You can set the value of a menu item's Checked property at runtime or design time. If you want to set its value at design time, you can set it within the Menu Editor by selecting the Checked check box. You also can set the value of the Checked property at design time within code, as follows:

MyMenuItem.Checked = True

When the value of the a menu item's Checked property is set to True, a check mark appears to the left of the menu item's caption.

Listing 13.1 shows the event procedure for the itmBlackOnWhite_Click() event. This is an example of how to set the Checked property of a menu item at runtime.


The Checked property isn't exclusive

You can set multiple checked events to True, if you want.


LISTING 13.1 13LIST01.TXT--Setting the Checked Property at Runtime

01 Private Sub itmBlackOnWhite_Click()
02    `Set the color scheme for Black on White
03    txtMain.BackColor = vbWhite
04    txtMain.ForeColor = vbBlack
05
06    `Set the menu checks accordingly
07    itmBlackOnWhite.Checked = True
08    itmWhiteOnBlack.Checked = False
09 End Sub

Cutting, Copying, and Pasting with the Clipboard Object

One of the more important features that the Windows operating system brought to computing was the capability to transfer data from one application to another via the Clipboard. The Clipboard is an area of memory reserved by Windows to which you send and from which you retrieve data. All applications have access to the Clipboard. Over time, the type of data that you can save to the Clipboard has become complex. You can save any registered Windows object, as well as simple text and numeric values.

Visual Basic allows your applications to access the Windows Clipboard through the Clipboard object. This object has no properties, but it does have a number of methods. Table 13.4 describes the various Clipboard methods.

TABLE 13.4  Clipboard Methods

Method Description
Clear Clears all data from the Clipboard
GetData Returns a graphic from the Clipboard
GetFormat Returns an integer that references the type of data in the Clipboard
GetText Retrieves ASCII text from the Clipboard
SetData Sends a graphic to the Clipboard
SetText Sends ASCII text to the Clipboard

The Cut, Copy, and Paste items on the Amazing Text Editor's Edit menu (see Figure 13.14) use the Clipboard object to set and retrieve text to and from the Clipboard. The following is the code for itmCopy_Click(), the event procedure that copies selected text to the Clipboard:

01 Private Sub itmCopy_Click()
02    Clipboard.SetText txtMain.SelText
03 End Sub

FIGURE 13.14 The Edit menu items use the conventional Windows shortcut keys.

The code takes the value of the SelText property of the TextBox and uses the Clipboard's SetText method to send the text to the Clipboard (line 2).

Listing 13.2 shows you how to retrieve text from the Clipboard. The listing is a snippet of code from the Paste menu item's Click event procedure.

LISTING 13.2 13LIST03.TXT--Retrieving Text from the Clipboard

01 Private Sub itmPaste_Click()
02  Dim Temp$              `Text from clipboard
03  Dim strLeft As String  `Holds text from left of cursor
04  Dim strRight As String `Holds text from right of cursor
05  Dim strFull As String  `Full text
06
07    `Get the text from the clipboard
08    Temp$ = Clipboard.GetText(vbCFText)
...
32 End Sub

Selecting Text in a TextBox

The Cut and Paste code in the Amazing Text Editor makes extensive use of copying selected text to and from the Clipboard. The code determines which text to copy by using the SelText property of the TextBox.


Using text boxes with menus

Although TextBoxes really don't have much to do with menus, this discussion is included simply to help you complete the Amazing Text Editor application.


The TextBox control has many standard Windows text-selection features built in to it. When you double-click a word that has been written into a TextBox, the TextBox automatically knows enough to highlight that word's characters. If you drag the mouse pointer across a line of text, that line will be highlighted automatically. When you click a TextBox, the text cursor will automatically be positioned between the characters you clicked.

The TextBox has three selection properties: SelStart, SelLength, and SelText. The value of SelStart is the string position of the cursor within a TextBox's contents. The value of SelLength is the number of characters highlighted during a selection process. The value of SelText is the characters highlighted during the selection process. The following code shows how to use the SelStart and SelLength properties to select a block of text (see Figure 13.15):

01 Private Sub Form_Click()
02    Text1.SelStart = 3
03    Text1.SelLength = 6
04 End Sub

FIGURE 13.15 The SelStart and SelLength properties make the TextBox a powerful control.

Not only can you read these properties, but you can also set them at runtime. SelStart and SelLength are pretty straightforward. If you set SelText at runtime, however, Visual Basic automatically inserts the string value of SelText into the contents of the TextBox at the cursor position, moving the existing text to accommodate this (see Figure 13.16):

01 Private Sub Command1_Click()
02    Text1.SelText = "Dog "
03 End Sub

FIGURE 13.16 SelText is a good property to use if you want to insert text into a TextBox repeatedly.

The code for the Amazing Text Editor also contains the Right(), Left(), and Len() functions, and the MsgBox statement. Chapter 12, "Working with Strings and Typecasting," discusses these functions in more detail, and Chapter 14, "Enhancing Your Programs with Forms and Dialog Boxes," explains how to use the MsgBox statement, as well as the MsgBox() function.


Previous chapterNext chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.