Make an infinite series of menus in C#


[infinite series of menus]

The example Create menu items at run time with images, shortcut keys, and event handlers in C# explains how to create menu items at run time. This example uses that technique to add new menu items to any submenu as it expands, making a practically infinite series of menus.

At design time, I gave the program a Tools main menu with a Tools menu item. Both of those menu items use the following DropDownOpening event handler to take action when they open.

// This menu item is opening.
// Add an item to this item's submenu.
private void mnuTools_DropDownOpening(object sender, EventArgs e)
{
    Console.WriteLine("mnuTools_DropDownOpening");
    // Remove this item's event handler.
    ToolStripMenuItem menu = sender as ToolStripMenuItem;
    menu.DropDownOpening -= mnuTools_DropDownOpening;

    // Find the submenu.
    ToolStripMenuItem submenu = 
        (ToolStripMenuItem)menu.DropDownItems[0];

    // Add the sub-submenu item.
    ToolStripMenuItem new_item = new ToolStripMenuItem("&Tools");
    new_item.DropDownOpening += mnuTools_DropDownOpening;
    submenu.DropDownItems.Add(new_item);
}

This event handler finds the menu item that is opening and removes its event handler so this code isn’t executed again for that item later.

It then finds the item’s single sub-item. That item has not yet been opened and does not yet contain any sub-items so, if the code did nothing else, the sub-item would appear as a normal menu item not a cascading menu. To fix that, the code adds a new menu item to the sub-item. It sets the new item’s DropDownOpening event handler to the same one used by the other menu items so it can continue the game when it is eventually opened.

(No this isn’t a good feature to add to a real application. It’s just an exercise in creating menus at run time. It’s also kind of amusing.)


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in menus, user interface and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *