Creating a main menu is straightforward, but it does involve several steps. Here is the
property.
menu associated with that top-level entry. This is also done by calling
Add( )
property.
4. Add the event handlers for each selection.
property associated with the form.
860
P a r t I I :
E x p l o r i n g t h e C # L i b r a r y
The following sequence shows how to create a File menu that contains three selections:
Open, Close, and Exit:
// Create a main menu object.
MainMenu = new MainMenu();
// Add a top-level menu item to the menu.
MenuItem m1 = new MenuItem("File");
MyMenu.MenuItems.Add(m1);
// Create File submenu.
MenuItem item1 = new MenuItem("Open");
m1.MenuItems.Add(item1);
MenuItem item2 = new MenuItem("Close");
m1.MenuItems.Add(item2);
MenuItem item3 = new MenuItem("Exit");
m1.MenuItems.Add(item3);
Let’s examine this sequence carefully. It begins by creating a
MainMenu
object called
MyMenu
. This object will be at the top of the menu structure. This object is instantiated by
use of the default constructor for
MainMenu
. This creates an empty menu.
Next, a menu item called
m1
is created. This is the File heading. It is created by using
this
MenuItem
constructor:
public MenuItem(string
caption
)
Here,
caption
specifies the text that is displayed by the item. In this case, it is “File.” This
menu item is then added directly to
MyMenu
and is a top-level selection.
Notice that when
m1
is added to
MyMenu
, it is done through the read-only
MenuItems
property.
MenuItems
is a collection of the menu items that form a menu. It is defined by
Menu
, which means it is part of both the
MainMenu
and
MenuItem
classes. It as shown here:
public Menu.MenuItemCollection MenuItems { get; }
To add a menu item to a menu, call
Add( )
on
MenuItems
, passing in a reference to the item
to add, as the example shows.
Next, the drop-down menu associated with File is created. Notice that these menu items
are added to the File menu item,
m1
. When one
MenuItem
is added to another, the added
item becomes part of the drop-down menu associated with the item to which it is added.
Thus, after the items
item1
through
item3
have been added to
m1
, selecting File will cause a
drop-down menu containing Open, Close, and Exit to be displayed.
Once the menu has been constructed, the event handlers associated with each entry
must be assigned. As explained, a user making a selection generates a
Click
event. Thus, the
following sequence assigns the handlers for
item1
through
item3
.
// Add event handlers for the menu items.
item1.Click += MMOpenClick;
item2.Click += MMCloseClick;
item3.Click += MMExitClick;
Therefore, if the user selects Exit,
MMExitClick( )
is executed.
www.freepdf-books.com