An appropriate menu on a Windows form based application can make the user’s life very much easier. They enable the user to navigate around the application can carry out tasks much more efficiently and they typically consist of items such as:
- File
- Edit
- Tools
- Help
The C# programmer can create such menus quickly and easily by using the C# MainMenu Object.
Using the C# MainMenu Object to Create a Menu
The C# MainMenu object is used to create menus in a Windows form based application. The first step, therefore, is to create an instance of the MainMenu Object:
The application now contains an empty menu to be used by the application. In this example the menu set up is contained with in s single function that can be called by the form:
The next step is to assign the newly created menu as the form’s menu:
And then to add some top level items:
If the form is compiled then it will show two menu items (“File” and “Help”). The next stage is to start populating the menu.
Creating a Sub Menu
Below each menu heading will be a sub menu. The programmer creates these sub menus by adding items to the top-level menu items:
If the form is recompiled then the “File” menu will now have “Exit” below it (when user clicks on the menu heading). The items in the sub menus will not do anything yet because they do not have any code associated with them. The programmer, therefore, now needs to add actions to the menus.
Adding Actions to Menus
The programmer adds actions to menus by creating C# event handlers. These will run a function when the user clicks on a menu item. In this example a function “close_app” will be run when the user clicks on the “Exit” menu item:
Obviously the programmer will need to create this new function, which could be something like:
Now the application will close if the user selects the “Exist” menu item.
Creating Sub-sub Menus
Each of the main menus consists of a sub menu and each sub menu consists of a set of menu items. These menu items may have actions associated with then (by adding event handlers) or they may themselves have further sub menus:
Here the “Help” menu will have a sub menu (“Web”) which has a further sub menu of (“Online Help” and “Current Version”). Obviously these menu items may also either have actions associated with them or have further sub menus.
Adding a Menu Separator
Many sub menus have their items divided into define groups. A separator can be used to make the groupings more obvious:
In the above example a bar will separate the “Web” and “About” items in the “Help” menu.
Summary
A programmer adds a menu to a C# Windows form based application by using the C# MainMenu object. Once the menu has been initialized and assigned to the form then menu items can be added to it.
These menu items can have either actions assigned to then (by using a C# event handler) or can have further sub menus added to them. In this way the C# programmer can build an application with easily accessible actions at the user’s fingertips.