The last menu-related topic in this chapter demonstrates how to iterate through all the items of a menu structure, including their submenus, at any depth. The main menu of an application can be accessed by the expression Me.MenuStrip1 (assuming that you’re using the default names). This is a reference to the top-level commands of the menu, which appear in the form’s menu bar. Each command, in turn, is represented by a ToolStripMenuItem object. All the items under a menu command form a ToolStripMenuItems collection, which you can scan to retrieve the individual commands.
The first command in a menu is accessed with the expression Me.MenuStrip1.Items(0); this is the File command in a typical application. The expression Me.MenuStrip1.Items(1) is the second command on the same level as the File command (typically, the Edit menu).
To access the items under the first menu, use the DropDownItems collection of the top command. The first command in the File menu can be accessed by this expression:
The same items can be accessed by name as well, and this is how you should manipulate the menu items from within your code. In unusual situations, or if you’re using dynamic menus to which you add and subtract commands at runtime, you’ll have to access the menu items through the DropDownItems collection.
The MapMenu Example
The MapMenu example demonstrates how to access the items of a menu from within your application’s code. The example’s main form contains a menu, a TextBox control, and a Button control that prints the menu’s structure in the TextBox. You can edit the menu before running the program, and the code behind the button will print the current structure of the menu items.
The code behind the Map Menu button iterates through the items of the form’s MenuStrip items and prints their names, as well as the names of their drop-down items, in the Output window. It scans all the members of the control’s Items collection and prints their captions. After printing each command’s caption, it calls the PrintSubMenu() subroutine, passing the current ToolStripMenuItem as an argument. The PrintSubMenu() subroutine iterates through the DropDownItems of the collection passed as an argument and prints their captions. If one of the items leads to a nested submenu, it calls itself, passing the current ToolStripMenuItem as an argument. You can open the MapMenu project with Visual Studio and examine its code.