Inherited Menus

It is not possible to use visual inheritance for menus, toolbars and status bars. This is annoying. There are a couple of tricks that can be done to add new items to the inherited menu.

Context Menu

  1. Create a context menu in the child class in the designer; this will support visual editing.
  2. Create a menu item at run time in the child for a new top level menu item.
  3. Set the DropDown event as the context menu.
  4. Insert the top level menu item into the main menu.
//Place in constructor or load event handler
ToolStripMenuItem menuItem = new ToolStripMenuItem("Tools");
menuItem.DropDown = contextMenuStripTools;
this.menuStripBase.Items.Insert(0, menuItem);

Menu Merging

The ToolStripManager class has a method that does menu merging like MDI applications.

public static bool Merge(
    ToolStrip sourceToolStrip,
    ToolStrip targetToolStrip
)

ToolStripManager.Merge documentation. Notice that it is a static method.

Menu Stealing

A menu item can only be in one menu at a time. It is possible to create a new menu and add visual items to it. At run time, move all the items from the new menu to the inherited menu. It is important to note that the items are moved to the new menu, not copied.

  1. Add a menu strip to the child. Add all the menu items to it.
  2. Add all the items from the main menu to the base menu.
  3. Access the items in the main menu in reverse order, since each item is moved to the base menu when it is inserted. A foreach cannot be used, since the item collection changes. AddRange won't work for the same reason.
 int count = 0;

 //Use this for loop, or a foreach, to see it crash
 //for (count = 0; count < max; count++)
 //A reverse pass through the items will do the trick
 for (count = menuStripMain.Items.Count - 1; count > -1; count--)
 {
   this.menuStripBase.Items.Insert(0, menuStripMain.Items[count]);
 }

The same technique can be used to add all the items from a context menu to the drop down items in a main form. This is how to insert menu items into the other menu, without removing items that might already exist.

 int count = 0;

 //Use this for loop, or a foreach, to see it crash
 //for (count = 0; count < max; count++)
 //A reverse pass through the items will do the trick
 for (count = contextMenu.Items.Count - 1; count > -1; count--)
 {
   menuStipItem.DrowDownItems.Insert(0, contextMenu.Items[count]);
 }

Removing Items

It is also possible to remove items. If you know the name of the item, then it can be removed by key. The key is the Name property. When items are added in the visual designer, the name is set to the variable name.

menuStrip.Items.RemoveByKey("fileMenuItem");

If you are adding an item in one place and removing it in another, then set the name of the item when it is created.

ToolStripMenuItem menuItem = new ToolStripMenuItem("Tools");
menuItem.Name = "ToolsItem";
...
menuStrip.Items.RemoveByKey("ToolsItem");