Make an infinitely cascading series of menu items in C#

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 expanding submenu. The results is a series of cascading menu items that grows as you drill deeper into it.

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.

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 funny.)

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.