Building Menus


When I said that Visual C# 2005 makes building menus easier than ever, I wasn't kidding. Building menus is now an immediately gratifying process. I can't stress enough how important it is to have good menus, and now that it's so easy to do, there's no excuse for not putting menus in an application.

Did you Know?

When running an application for the first time, users often scan the menus before opening a manual. (Most users never open the manual!) When you provide comprehensive menus, you make your program easier to learn and use.


Creating Top-Level Menu Items

Adding menus to a form is accomplished by way of a control: the Main Menu control. The Menu Strip control is a bit odd in that it's the only control I know of (besides the context menu control discussed later in this hour) that sits at the bottom of the form in the space reserved for controls without an interface (like a Timer control), yet actually has a visible interface on the form.

Follow these steps to get started:

1.

You're going to be using the Picture Viewer project that you worked on in Hour 8, "Using Advanced Controls," so open that project now.

2.

Double-click frmViewer.cs in the Solution Explorer to display the main picture viewer form in design view.

3.

You're going to need room at the top of the form, so change the Size.Height property of the form to 375.

4.

Change the PictureBox's Location to 8,52 and its Size to 282,279.

5.

Next, select all of the controls on the form except the picture box by Shift-clicking them or lassoing them. Make sure to get the X and Y labels! When they're all selected, click and drag the Select Picture button until its top aligns with the picture box (when you drag, all controls should move with the Select Picture button). Your form should now look like Figure 9.1.

Figure 9.1. You'll need space for menus and tool-bars at the top of your form.


6.

Add a new Menu Strip control to your form by double-clicking the MenuStrip item in the toolbox and change its name to mnuMainMenu. As you can see, the control is added to the pane at the bottom of the Form Designer. Take a look at the top of the formyou'll see the text Type Here (see Figure 9.2).



Figure 9.2. A menu has no items when first added to a form.


7.

Click this text Type Here and type &File and press Enter. As you begin typing, Visual C# displays two new boxes that say Type Here (see Figure 9.3).

Figure 9.3. Creating a menu item automatically prepares the control for more items.


Notice the Properties window (if it's not visible, press F4 to show it). The text you just entered creates a new menu item. Each menu item is an object, and therefore, the item has properties. By default, Visual C# gives the menu the name FileToolStripMenuItem. It's a long name, but it gets the job done.

You might be wondering why I had you enter the ampersand (&) in front of the word File. Take a look at your menu now, and you'll see that Visual C# doesn't display the ampersand; instead, it displays the text with the F underlined, as in File. The ampersand, when used in the Text property of a menu item, tells Visual C# to underline the character immediately following it. For top-level menu items, such as the File item you just created, this underlined character is known as an accelerator key. Pressing Alt + an accelerator key opens the menu as if the user had clicked it. You should avoid assigning the same accelerator key to more than one top-level menu item on a form. To avoid conflicts, you can make any character the accelerator character, not just the first character(i.e. F&ile for File). When the menu item appears on a drop-down menu (as opposed to being a top-level item), the underlined character is called a hotkey. When a menu is visible (open), the user can press a hotkey to trigger the corresponding menu item the same as if it were clicked. Again, don't use the same hotkey for more than one item on the same menu.

8.

Click the Type Here text that appears to the immediate right of the File item, enter &Tools, and press Enter. Visual C# gives you two more Type Here itemsthe same as when you entered the File item. Adding new menu items is a matter of clicking a Type Here box and entering the text for an item.

By the Way

If you click a Type Here box below an existing menu item, you'll add a new item to the same menu as the item above the box. If you click the Type Here box to the right of a menu item, you'll create a submenu using the menu to the left of the box as the entry point for the submenu. As you've already seen, clicking the Type Here box along the top of the menu bar creates a top-level menu.


Creating Menu Items for a Top-Level Menu

You can create as many top-level menus as you have room for on a form. For the Picture Viewer, the File and Tools menus are adequate. Now, you need to create the menu items that a user can select for these top-level menus. Follow these steps to create the menu items:

1.

Click once more on the File item to display a Type Here box below it. Click this Type Here box, enter &Open Picture..., and then press Enter.

2.

Change the name of the new item to mnuOpenPicture (you'll need to click it to give it the focus before you can change its properties in the Properties Window).

3.

Click the Type Here box below the Open Picture item you created, type &Quit, and then press Enter. Change the name of the new item to mnuQuit. Now is a good time to save your work, so click Save All on the toolbar.

4.

Click the Tools menu to select it. This displays a Type Here box to the right and below the Tools item. Click the Type Here box below the Tools menu, type &Draw Border, and then press Enter. Change the name of the new item to mnuDrawBorder.

5.

Now, this can be tricky. Hover the pointer over the Type Here box below the Draw Border item. A small drop arrow appears. Click this arrow and select Separator (see Figure 9.4). This drop-down is used to specify what type of item you want on the menu. You can create a combo box or text box or, as in this case, a separator to isolate groups of unrelated menu items.

Figure 9.4. You can create text boxes, combo boxes, and separators in addition to regular menu items.


6.

After choosing Separator, a line appears under Draw Border, and a new Type Here box appears. Click this box to select it, enter the text &Options..., and then press Enter to create the menu item. Change the name of this new item to mnuOptions.

7.

Finally, click the picture box or some other control to stop editing the menu.

Moving and Deleting Menu Items

Deleting and moving menu items are even easier than adding new items. To delete a menu item, right-click it and choose Delete from the context menu that appears (or simply click it to select it and press Delete). To move an item, drag it from its current location and drop it in the location in which you want it placed. Unfortunately, items can only be moved within the same menu.

Creating Checked Menu Items

A menu item that isn't used to open a submenu can display a check mark next to its text. Check marks are used to create menu items that have statethe item is either selected or it isn't. You're now going to create a checked menu item. Remember from Hour 8 the check box you created for the Options form? It was used to specify whether the user should be prompted before the Picture Viewer closes. You're now going to create a menu item for this as well. Follow these steps:

1.

Click the File menu to open it up.

2.

Click the Type Here box below the Quit menu item, enter Confirm on Exit, and press Enter. Change the Name of the new item to mnuConfirmOnExit.

3.

Right-click on Confirm on Exit and choose Checked from the shortcut menu that appears (see Figure 9.5). If your menu is different than the one in Figure 9.5, click a different menu item and then right-click the Confirm on Exit item once more. You could have also clicked the menu item once and changed its Checked property in the Properties window.

Figure 9.5. Menu items can be used to indicate state.


4.

Next, click and drag the Confirm on Exit item and drop it on the Quit menu item. This moves the item above the Quit item. Your menu now looks like Figure 9.6.

Figure 9.6. You have complete control over the structure of your menus.


Press F5 to run the project. The menu appears on your form, just as you designed it (see Figure 9.7). Click the File menu to open it and then click Quit; nothing happens. In fact, the checked state of your menu item doesn't even change if you click that item. In the next section, I'll show you how to add code to menu items to make them actually do something (as well as change their checked state).

Figure 9.7. Menus appear at runtime the same as they do at design time.


Stop the project now and save your work.

Programming Menus

Every menu item is a unique objectyou could actually edit each item by clicking an item once to select it and then changing the item's properties in the Properties window. Although individual menu items aren't controls per se, adding code behind them is similar to adding code behind a control. You're now going to add code to menu items you created.

Follow these steps to create the code for the menus:

1.

Click the File menu now to open it.

2.

Double-click the Open Picture menu item. Just as when you double-click a control, Visual C# displays the code editor with the default event for the menu item you've clicked. For menu items, this is the Click event.

3.

Enter the following code:

// Show the open file dialog box. if (ofdSelectPicture.ShowDialog() == DialogResult.OK) {    // Load the picture into the picture box.    picShowPicture.Image = Image.FromFile(ofdSelectPicture.FileName);    // Show the name of the file in the form's caption.    this.Text = string.Concat("Picture Viewer(" + ofdSelectPicture.FileName + ")"); }


This is the exact code you entered for the Select Picture button you created in Hour 1, "Jumping In with Both Feet: A Visual C# 2005 Programming Tour," so I won't discuss it here.

4.

Click the frmViewer.cs [Design] tab in the form designer to switch back to the form designer for the Picture Viewer form.

5.

Double-click the Confirm on Exit menu item to access its Click event. Enter the following code statement:

mnuConfirmOnExit.Checked = !(mnuConfirmOnExit.Checked);


When the item Confirm on Exit is clicked, this code sets the item's checked state to the opposite of the item's current checked state. The ! operator is used to perform a negation of a Boolean (true or false) value. Don't worry; I discuss this in detail in Hour 12, "Performing Arithmetic, String Manipulation, and Date/Time Adjustments." For now, realize that if the current value of the Checked property is True, ! returns False. If Checked is currently False, ! returns True. Therefore, the checked value toggles between True and False each time the menu item is clicked.

6.

Double-click frmViewer.cs in the Solution Explorer window to switch back to the Form Designer for the Picture Viewer form again.

7.

Double-click the Quit menu item to access its Click event and enter the following code:

this.Close();


Again, recall from Hour 1 that this statement simply closes the form, which has the effect of closing the application because it's the only form that's loaded.

8.

Return to the form viewer yet again, click Tools to display the Tools menu, and then double-click the Draw Border menu item to access its Click event. Enter the following code:

Graphics objGraphics = null; objGraphics = this.CreateGraphics(); objGraphics.Clear(SystemColors.Control); objGraphics.DrawRectangle(Pens.Blue, picShowPicture.Left - 1, picShowPicture.Top - 1,       picShowPicture.Width + 1, picShowPicture.Height + 1); objGraphics.Dispose();


This code is also directly from Hour 1, so refer to that chapter for the specifics on how this code works.

9.

Return to the Form Designer, double-click the Options menu item, and enter the following two code statements in its Click event:

frmOptions frmOptionsDialog = new frmOptions(); frmOptionsDialog.ShowDialog();


You have just added all the code necessary for your menu to function. Follow these steps to test your work:

1.

Press F5 to run the project. Open the File menu by pressing Alt+F (remember, the F is the accelerator key).

2.

Next, click the Confirm on Exit button. The menu closes, so click File again to open it and notice that the item is no longer checked. Clicking it again would check it.

3.

Click all the menu items except Quit to make sure that they work as expected. When you're finished, choose Quit from the File menu to close the running project.

If you selected Confirm on Exit, you might have noticed that you weren't asked whether you really wanted to quit. That's because the quit code hasn't been written to consider the checked state of the Ask Before Closing button. You'll be hooking up this item, as well as all of the options, in Hour 11, "Using Constants, Data Types, Variables, and Arrays."

Did you Know?

When designing your menus, look at some of the many popular Windows applications available and consider the similarities and differences between their menus and yours. Although your application might be unique and therefore have different menus than other applications, there are probably similarities as well (such as Cut, Copy, Paste, Open, etc.). When possible, make menu items in your application follow the same structure and design as similar items in the popular programs. This will shorten the learning curve of your application, reduce user frustration, and save you time.


Implementing Context Menus

Context menus (also called shortcut menus) are the pop-up menus that appear when you right-click an object on a form. Context menus get their name from the fact that they display context-sensitive choicesmenu items that relate directly to the object that's right-clicked. Most Visual C# controls have a default context menu (also called a shortcut menu), but you can assign custom context menus if you want. Creating context menus is much like creating regular menus. Context menus, however, are created using a different control: the Context Menu Strip control.

Follow these steps to implement a custom context menu in your project:

1.

Display the frmViewer.cs form in the Form Designer.

2.

Add a new context menu strip to the form by double-clicking the Context Menu Strip item in the toolbox. Like the MainMenucontrol, the Context Menu Strip control is placed in the pane below the Form Designer. Change its name to mnuPictureContext.

3.

When the Context Menu Strip control is selected, a context menu appears toward the top for editing. Click the Type Here box, enter the text Draw Border (see Figure 9.8), and press Enter to create the menu item. You've just created a context menu with a single menu item.

Figure 9.8. Context menus are edited much like regular menus.


4.

Double-click the new menu item to access its Click event and enter the following code:

Graphics objGraphics = null; objGraphics = this.CreateGraphics(); objGraphics.Clear(SystemColors.Control); objGraphics.DrawRectangle(Pens.Blue, picShowPicture.Left - 1, picShowPicture.Top - 1,       picShowPicture.Width + 1, picShowPicture.Height + 1); objGraphics.Dispose();


Yes, this is the exact same code you entered for the Draw Border menu item and the Draw Border button. It seems sort of redundant to enter the same code in three places doesn't it? In Hour 10, "Creating and Calling Methods," I'll show you how to share code so that you don't have to enter it in multiple places!

5.

Double-click frmViewer.cs in the Solution Explorer to return to the designer for the Picture Viewer form.

6.

Linking a control to a context menu is accomplished by setting a property. Click the picture box on the form now to select it, and then change the ContextMenuStrip property of the text box to mnuPictureContext; the context menu is now linked to the picture box.

7.

Press F5 to run the project and right-click the picture box. You'll see the context menu shown in Figure 9.9. Go ahead and choose Draw Border, and the border will be drawn.

Figure 9.9. Context menus make handy shortcuts.


8.

Stop the project and save your work.

Assigning Shortcut Keys to Menu Items

If you've spent any time learning a Microsoft application, you've most likely learned some keyboard shortcuts. For example, pressing Alt+P in any application that prints has the same effect as opening the File menu and choosing Print.

Add shortcuts to your menus now by following these steps:

1.

Click the File menu at the top of the form to open it and then click Open Picture to select it.

2.

In the Properties window, click the ShortcutKeys property and then click the down arrow that appears. This drop-down allows you to define a shortcut key for the selected menu item (see Figure 9.10).

Figure 9.10. A shortcut key is assigned using the ShortcutKeys property of a menu item.


3.

Click Ctrl and then select O (for Open) from the key drop-down menu; then click another property to close the drop-down.

4.

Press F5 to run the project once more. Next, press Ctrl+O, and the application behaves just as though you opened the File menu and clicked the Open Picture item.

Did you Know?

Although it isn't always possible, try to assign logical shortcut key combinations. The meaning of F6 is hardly intuitive, for example. But, when assigning modifiers such as Ctrl with another character, you have some flexibility. For instance, the key combination of Ctrl+Q might be a more intuitive shortcut key for Quit than Ctrl+T. Again, if the menu item is the same or similar to a menu item in a commercial application, use the same shortcut key as the commercial application.


Stop the running project and save your work before continuing.




Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net