0

I managed to implement Dynamically Adding Menu Items

This allows dynamically adding menu command. This is nice but its a flat 1-level dynamic menu.

Is it possible to create a dynamic sub-menu and attach it to a command?

The static way is to create: menu->group->button->group->menu but I did not find and exposed object for that.

Appreciate the help!

Thanks.

Shlomi Assaf
  • 2,178
  • 18
  • 19

1 Answers1

1

I understand that it is a little bit out-dated question, but since I've experienced the same problem (just in vspackage for vs 2010) I'm writing a workaround which I found. Maybe it will save somebody a couple of hours or days.

At first you need to find location where you want to add your menus/submenus, something like this:

EnvDTE.DTE dte = GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
//EnvDTE80.Commands2 cmds = (EnvDTE80.Commands2)dte.Commands;
CommandBars cmdBars = dte.CommandBars as CommandBars;
CommandBar mainMenu = cmdBars.ActiveMenuBar;
CommandBarPopup parentBar = (CommandBarPopup)mainMenu.Controls["MyStaticBar"];

Then you can add new menu groups (CommandBarPopup instances) and menu items (CommandBarButton instances) like this for menu group:

CommandBarPopup newPopup = (CommandBarPopup)parentBar.Controls.Add(MsoControlType.msoControlPopup);
newPopup.Caption = "My Dynamic Menu group;
newPopup.Enabled = true;
newPopup.Visible = true;

And this for menu item

   CommandBarButton button = (CommandBarButton)newPopup.Controls.Add(MsoControlType.msoControlButton);
    button.Caption = "Custom menu item";
    button.Enabled = true;
    button.Visible = true;
    button.Click += new _CommandBarButtonEvents_ClickEventHandler(ExecuteCustomCommand);

There is also a way to do this through dte.Commands (custed eiter to EnvDTE.Commands or to EnvDTE80.Commands2), but I didn't use it, which means that I didn't investigate it fully and didn't ensure that it works in this particular case.

P.S. You will need to add Microsoft.VisualStudio.CommandBars.dll to references to make this work (or you will need to cast objects to dynamic)

skv
  • 85
  • 9