Home
News
Weblog
Kompetenzen
Referenzen
Media
Unternehmen
Kontakt

 SSMS: Adding submenus to context menu

Jetzt kommentieren!

Publiziert von Stefan Schwedt

6. November 2008 _ 4:51

If you want to add a menu item to the ObjectExplorer’s context menu, the proceeding is quite simple.
Create a class that inherits from ToolsMenuItemBase

public class MenuItem : ToolsMenuItemBase
{
    public MenuItem()
    {
         this.Text = "New menu item";
    }
 
    protected override void Invoke()
    {
        // do something
    }
 
    public override object Clone()
    {
        return new MenuItem();
    }
}

and attach it to the ObjectExplorer’s menu

IObjectExplorerService objectExplorer = ServiceCache.GetObjectExplorer();
objectExplorer.GetSelectedNodes(out nodeCount, out nodes);
INodeInformation node = (nodeCount > 0 ? nodes[0] : null);
 
if (_tableMenu == null)
{
    _tableMenu = (HierarchyObject)node.GetService(typeof(IMenuHandler));
 
    MenuItem item = new MenuItem();
    _tableMenu.AddChild(string.Empty, item);
}

What if you now intend to create a menu item that again contains a sub menu? ToolsMenuItemBase provides a method called AddChild. Using this method should be the obvious way to create sub menus.
But any call like item.AddChild(string.Empty, new SubMenuItem()) simply does nothing.

Using Reflector, I found a solution to achieve the desired behaviour.
The trick is to implement an interface called IWinformsMenuHandler. You will need to create a method GetMenuItems. It is here where you can create a new menu hierarchy.

The new class looks like this:

public class MenuItem : ToolsMenuItemBase, IWinformsMenuHandler
{
	public MenuItem()
	{
	}
 
	protected override void Invoke()
	{
	}
 
	public override object Clone()
	{
		return new MenuItem();
	}
 
	public System.Windows.Forms.ToolStripItem[] GetMenuItems()
	{
		ToolStripMenuItem item = new ToolStripMenuItem("Menu Item");
 
		ToolStripMenuItem subItem = new ToolStripMenuItem("Sub item");
		subItem.Click += new EventHandler(SubItem_Click);
 
		item.DropDownItems.Add(subItem);
		item.DropDownItems.Add(new ToolStripSeparator());
		item.DropDownItems.Add(new ToolStripMenuItem("Sub item2"));		
 
		return new ToolStripItem[] { item };
	}
}

When implementing IWinformsMenuHandler setting the properties of ToolsMenuItemBase will be useless. E.g. this.Text = "Menu item" will be relpaced by ToolStripMenuItem item = new ToolStripMenuItem("Menu Item");. Also Invoke() will never be called, but the event handler of your ToolStripMenuItem.

Leave a Reply