15.2 Menus

Menus provide groups of related commands for Windows Forms apps. Although these commands depend on the program, some—such as Open and Save—are common to many apps. Menus are an integral part of GUIs, because they organize commands without “cluttering” the GUI.

In Fig. 15.1, an expanded menu from Visual Studio lists various commands (called menu items), plus submenus (menus within a menu). The top-level menus appear in the left portion of the figure, whereas any submenus or menu items are displayed to the right. The menu that contains a menu item is called that menu item’s parent menu. A menu item that contains a submenu is considered to be the parent of that submenu.

Menus can have Alt key shortcuts (also called access shortcuts, keyboard shortcuts or hotkeys), which are accessed by pressing Alt and the underlined letter—for example, Alt + F typically expands the File menu. Menu items can have shortcut keys as well (combinations of Ctrl, Shift, Alt, F1, F2, letter keys, and so on). Some menu items display checkmarks, usually indicating that multiple options on the menu can be selected at once.

Fig. 15.1 Menus, submenus and menu items.

To create a menu, open the Toolbox and drag a MenuStrip control onto the Form. This creates a menu bar across the top of the Form (below the title bar) and places a MenuStrip icon in the component tray. To select the MenuStrip, click this icon. You can now use Design mode to create and edit menus for your app. Menus, like other controls, have properties and events, which can be accessed through the Properties window.

To add menu items to the menu, click the Type Here TextBox (Fig. 15.2) and type the menu item’s name. This action adds an entry to the menu of type ToolStripMenuItem. After you press the Enter key, the menu item name is added to the menu. Then more Type Here TextBoxes appear, allowing you to add items underneath or to the side of the original menu item (Fig. 15.3).

To create an access shortcut, type an ampersand (&) before the character to be underlined. For example, to create the File menu item with the letter F underlined, type &File. To display an ampersand, type &&. To add other shortcut keys (e.g., Ctrl + F9) for menu items, set the ShortcutKeys property of the appropriate ToolStripMenuItems. To do this, select the down arrow to the right of this property in the Properties window. In the window that appears (Fig. 15.4), use the CheckBoxes and drop-down list to select the shortcut keys. When you’re finished, click elsewhere on the screen. You can hide the shortcut keys by setting property ShowShortcutKeys to false, and you can modify how the shortcut keys are displayed in the menu item by modifying property ShortcutKeyDisplayString.

Fig. 15.2 Editing menus in Visual Studio.

Fig. 15.3 Adding ToolStripMenuItems to a MenuStrip.

Fig. 15.4 Setting a menu item’s shortcut keys.

Look-and-Feel Observation 15.1

Buttons can have access shortcuts. Place the & symbol immediately before the desired character in the Button’s text. To press the button by using its access key in the running app, the user presses Alt and the underlined character. If the underline is not visible when the app runs, press the Alt key to display the underlines.

You can remove a menu item by selecting it and pressing the Delete key. Menu items can be grouped logically by separator bars, which are inserted by right clicking the menu and selecting Insert > Separator or by typing “- ” for the text of a menu item.

In addition to text, Visual Studio allows you to easily add TextBoxes and ComboBoxes (drop-down lists) as menu items. When adding an item in Design mode, you may have noticed that before you enter text for a new item, you’re provided with a drop-down list. Clicking the down arrow (Fig. 15.5) allows you to select the type of item to add—Menu-Item (of type ToolStripMenuItem, the default), ComboBox (of type ToolStripComboBox) and TextBox (of type ToolStripTextBox). We focus on ToolStripMenuItems. [Note: If you view this drop-down list for menu items that are not on the top level, a fourth option appears, allowing you to insert a separator bar.]

Fig. 15.5 Menu-item options.

ToolStripMenuItems generate a Click event when selected. To create an empty Click event handler, double click the menu item in Design mode. Common actions in response to these events include displaying dialogs and setting properties. Common menu properties and a common event are summarized in Fig. 15.6.

Look-and-Feel Observation 15.2

It’s a convention to place an ellipsis () after the name of a menu item (e.g., Save As…) that requires the user to provide more information—typically through a dialog. A menu item that produces an immediate action without prompting the user for more information (e.g., Save) should not have an ellipsis following its name.

Fig. 15.6 MenuStrip and ToolStripMenuItem properties and an event.

MenuStrip and ToolStripMenuItem properties and an event Description
MenuStrip Properties
RightToLeft Causes text to display from right to left. This is useful for languages that are read from right to left.
ToolStripMenuItem Properties
Checked Indicates whether a menu item is checked. The default value is false, meaning that the menu item is unchecked.
CheckOnClick Indicates that a menu item should appear checked or unchecked as it is clicked.
ShortcutKeyDisplayString Specifies text that should appear beside a menu item for a shortcut key. If left blank, the key names are displayed. Otherwise, the text in this property is displayed for the shortcut key.
ShortcutKeys Specifies the shortcut key for the menu item (e.g., <Ctrl>-F9 is equivalent to clicking a specific item).
ShowShortcutKeys Indicates whether a shortcut key is shown beside menu item text. The default is true, which displays the shortcut key.
Text Specifies the menu item’s text. To create an Alt access shortcut, precede a character with & (e.g., &File to specify a menu named File with the letter F underlined).
Common ToolStripMenuItem Event
Click Generated when an item is clicked or a shortcut key is used. This is the default event when the menu is double clicked in the designer.

Class MenuTestForm (Fig. 15.7) creates a simple menu on a Form. The Form has a top-level File menu with menu items About (which displays a MessageBox) and Exit (which terminates the program). The program also includes a Format menu, which contains menu items that change the format of the text on a Label. The Format menu has submenus Color

Fig. 15.7 Using menus for changing text font and color.

Alternate View

  1      // Fig. 15.7: MenuTestForm.cs
  2      // Using Menus to change font colors and styles.
  3      using System;
  4      using System.Drawing;
  5      using System.Windows.Forms;
  6
  7      namespace MenuTest
  8      {
  9         // our Form contains a Menu that changes the font color
 10         // and style of the text displayed in Label
 11         public partial class MenuTestForm : Form
 12         {
 13            // constructor
 14            public MenuTestForm()
 15            {
 16               InitializeComponent();
 17            }
 18
 19            // display MessageBox when About ToolStripMenuItem is selected
 20            private void aboutToolStripMenuItem_Click(
 21               object sender, EventArgs e)
 22            {
 23                MessageBox.Show("This is an example
of using menus.", "About",
 24                   MessageBoxButtons.OK, MessageBoxIcon.Information);
 25            }
 26
 27            // exit program when Exit ToolStripMenuItem is selected
 28            private void exitToolStripMenuItem_Click(object sender, EventArgs e)
 29            {
 30                Application.Exit();
 31            }
 32
 33            // reset checkmarks for Color ToolStripMenuItems
 34            private void ClearColor()
 35            {
 36               // clear all checkmarks
 37               blackToolStripMenuItem.Checked = false;
 38               blueToolStripMenuItem.Checked = false;
 39               redToolStripMenuItem.Checked = false;
 40               greenToolStripMenuItem.Checked = false;
 41            }
 42
 43            // update Menu state and color display black
 44            private void blackToolStripMenuItem_Click(
 45               object sender, EventArgs e)
 46            {
 47               // reset checkmarks for Color ToolStripMenuItems
 48               ClearColor();
 49
 50               // set color to Black
 51               displayLabel.ForeColor = Color.Black;
 52               blackToolStripMenuItem.Checked = true;
 53            }
 54
 55            // update Menu state and color display blue
 56            private void blueToolStripMenuItem_Click(object sender, EventArgs e)
 57            {
 58                // reset checkmarks for Color ToolStripMenuItems
 59                ClearColor();
 60
 61                // set color to Blue
 62                displayLabel.ForeColor = Color.Blue;
 63                blueToolStripMenuItem.Checked = true;
 64             }
 65
 66             // update Menu state and color display red
 67             private void redToolStripMenuItem_Click(
 68                object sender, EventArgs e)
 69             {
 70                // reset checkmarks for Color ToolStripMenuItems
 71                ClearColor();
 72
 73                // set color to Red
 74                displayLabel.ForeColor = Color.Red;
 75                redToolStripMenuItem.Checked = true;
 76             }
 77
 78             // update Menu state and color display green
 79             private void greenToolStripMenuItem_Click(
 80                object sender, EventArgs e)
 81             {
 82                // reset checkmarks for Color ToolStripMenuItems
 83                ClearColor();
 84
 85                // set color to Green
 86                displayLabel.ForeColor = Color.Green;
 87                greenToolStripMenuItem.Checked = true;
 88             }
 89
 90             // reset checkmarks for Font ToolStripMenuItems
 91             private void ClearFont()
 92             {
 93                // clear all checkmarks
 94                timesToolStripMenuItem.Checked = false;
 95                courierToolStripMenuItem.Checked = false;
 96                comicToolStripMenuItem.Checked = false;
 97             }
 98
 99             // update Menu state and set Font to Times New Roman
 100            private void timesToolStripMenuItem_Click(
 101               object sender, EventArgs e)
 102            {
 103               // reset checkmarks for Font ToolStripMenuItems
 104               ClearFont();
 105
 106               // set Times New Roman font
 107               timesToolStripMenuItem.Checked = true;
 108               displayLabel.Font = new Font("Times New Roman", 14,
 109                   displayLabel.Font.Style);
 110            }
 111
 112            // update Menu state and set Font to Courier
 113            private void courierToolStripMenuItem_Click(
 114               object sender, EventArgs e)
 115            {
 116               // reset checkmarks for Font ToolStripMenuItems
 117               ClearFont();
 118
 119               // set Courier font
 120               courierToolStripMenuItem.Checked = true;
 121               displayLabel.Font = new Font("Courier", 14,
 122                  displayLabel.Font.Style);
 123            }
 124
 125            // update Menu state and set Font to Comic Sans MS
 126            private void comicToolStripMenuItem_Click(
 127               object sender, EventArgs e)
 128            {
 129               // reset checkmarks for Font ToolStripMenuItems
 130               ClearFont();
 131
 132               // set Comic Sans font
 133               comicToolStripMenuItem.Checked = true;
 134               displayLabel.Font = new Font("Comic Sans MS", 14,
 135                  displayLabel.Font.Style);
 136            }
 137
 138            // toggle checkmark and toggle bold style
 139            private void boldToolStripMenuItem_Click(object sender, EventArgs e)
 140            {
 141               // toggle checkmark
 142               boldToolStripMenuItem.Checked = !boldToolStripMenuItem.Checked;
 143
 144               // use Xor to toggle bold, keep all other styles
 145               displayLabel.Font = new Font(displayLabel.Font,
 146                  displayLabel.Font.Style ^ FontStyle.Bold);
 147            }
 148
 149            // toggle checkmark and toggle italic style
 150            private void italicToolStripMenuItem_Click(
 151               object sender, EventArgs e)
 152            {
 153               // toggle checkmark
 154               italicToolStripMenuItem.Checked =
 155                  !italicToolStripMenuItem.Checked;
 156
 157               // use Xor to toggle italic, keep all other styles
 158                displayLabel.Font = new Font(displayLabel.Font,
 159                   displayLabel.Font.Style ^ FontStyle.Italic);
 160            }
 161        }
 162 }

Create the GUI

To create this GUI, begin by dragging the MenuStrip from the ToolBox onto the Form. Then use Design mode to create the menu structure shown in the sample outputs. The File menu (fileToolStripMenuItem) has menu items

  • About (aboutToolStripMenuItem) and

  • Exit (exitToolStripMenuItem).

The Format menu (formatToolStripMenuItem) has two submenus. The first submenu, Color (colorToolStripMenuItem), contains menu items

  • Black (blackToolStripMenuItem),

  • Blue (blueToolStripMenuItem),

  • Red (redToolStripMenuItem) and

  • Green (greenToolStripMenuItem).

The second submenu, Font (fontToolStripMenuItem), contains menu items

  • Times New Roman (timesToolStripMenuItem),

  • Courier (courierToolStripMenuItem),

  • Comic Sans (comicToolStripMenuItem),

  • a separator bar (dashToolStripMenuItem),

  • Bold (boldToolStripMenuItem) and Italic (italicToolStripMenuItem).

Handling the Click Events for the About and Exit Menu Items

The About menu item in the File menu displays a MessageBox when clicked (lines 20–25). The Exit menu item closes the app through static method Exit of class Application (line 30). Class Application’s static methods control program execution. Method Exit causes our app to terminate.

Color Submenu Events

We made the items in the Color submenu (Black, Blue, Red and Green) mutually exclusive—the user can select only one at a time (we explain how we did this shortly). To indicate that a menu item is selected, we will set each Color menu item’s Checked property to true. This causes a check to appear to the left of a menu item.

Each Color menu item has its own Click event handler. The method handler for color Black is blackToolStripMenuItem_Click (lines 44–53). Similarly, the event handlers for colors Blue, Red and Green are blueToolStripMenuItem_Click (lines 56–64), redToolStripMenuItem_Click (lines 67–76) and greenToolStripMenuItem_Click (lines 79–88), respectively. Each Color menu item must be mutually exclusive, so each event handler calls method ClearColor (lines 34–41) before setting its corresponding Checked property to true. Method ClearColor sets the Checked property of each color ToolStripMenuItem to false, effectively preventing more than one menu item from being selected at a time. In the designer, we initially set the Black menu item’s Checked property to true, because at the start of the program, the text on the Form is black.

Software Engineering Observation 15.1

The mutual exclusion of menu items is not enforced by the MenuStrip, even when the Checked property is true. You must program this behavior.

Font Submenu Events

The Font menu contains three menu items for fonts (Courier, Times New Roman and Comic Sans) and two menu items for font styles (Bold and Italic). We added a separator bar between the font and font-style menu items to indicate that these are separate options. A Font object can specify only one font at a time but can set multiple styles at once (e.g., a font can be both bold and italic). We set the font menu items to display checks. As with the Color menu, we must enforce mutual exclusion of these items in our event handlers.

Event handlers for font menu items Times New Roman, Courier and Comic Sans are timesToolStripMenuItem_Click (lines 100–110), courierToolStripMenuItem_Click (lines 113–123) and comicToolStripMenuItem_Click (lines 126–136), respectively. These event handlers are similar to those of the Color menu items. Each clears the Checked properties for all font menu items by calling method ClearFont (lines 91–97), then sets the Checked property of the menu item that raised the event to true. This enforces the mutual exclusion of the font menu items. In the designer, we initially set the Times New Roman menu item’s Checked property to true, because this is the original font for the text on the Form. The event handlers for the Bold and Italic menu items (lines 139–160) use the bitwise logical exclusive OR (^) operator to combine font styles, as we discussed in Chapter 14.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset