How to find Visual Studio command bars

When developing a Visual Studio Addin it is a common task to add custom commands to existing menus and toolbars. It is a common problem too, not to find the proper command bar (we have to traverse all command bars to see its names, the names are not unique, etc). In these two posts: Using IVsProfferCommands to retrieve a Visual Studio CommandBar and  Using EnableVSIPLogging to identify menus and commands with VS 2005 + SP1 it is very well explained how to solve this problem.

The answer relies on the fact that every toolbar and menu is uniquely identified in Visual Studio by a GUID,Id pair. In order to see which is the GUID, Id pair for a given command, you must:

  • Add or change the registry key HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\General\EnableVSIPLogging to 1.

  • Click on the toolbar or menu you want identify while keeping CTRL+SHIFT pressed. This will show a dialog with the command bar properties. Take note of the Guid and the CmdID:

  • From the Addin, use the following code to add your command in the desired command bar:

 

private void AddMyCustomCommand()

 

{

   

 

 

    object[] contextGuids = new object[0];

 

    myCommand = ((Commands2)this._applicationObject.Commands).AddNamedCommand2(this._addInInstance, 

             partialCommandName,displayName, tooltip, true, null, ref contextGuids,

 

            (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,

 

            (int)vsCommandStyle.vsCommandStyleText,vsCommandControlType.vsCommandControlTypeButton);

 

    CommandBar ownerBar = FindCommandBar(new Guid("{9AEB9524-82C6-40B9-9285-8D85D3DBD4C4}"), 1280);

 

    myControl = workflowCommand.AddControl(ownerBar, 1) as CommandBarButton;   

}

 

private CommandBar FindCommandBar(Guid guidCmdGroup, uint menuID)

 

{

 

   // Retrieve IVsProfferComands via DTE's IOleServiceProvider interface

 

   IOleServiceProvider sp = (IOleServiceProvider)_applicationObject;

 

   Guid guidSvc = typeof(IVsProfferCommands).GUID;

 

   Object objService;

 

   sp.QueryService(ref guidSvc, ref guidSvc, out objService);

 

   IVsProfferCommands vsProfferCmds = (IVsProfferCommands)objService;

 

   return vsProfferCmds.FindCommandBar(IntPtr.Zero, ref guidCmdGroup, menuID) as CommandBar;

 

}

[ComImport,Guid("6D5140C1-7436-11CE-8034-00AA006009FA"),

 

InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]

 

internal interface IOleServiceProvider

 

{

 

    [PreserveSig]

 

    int QueryService([In]ref Guid guidService, [In]ref Guid riid,

 

       [MarshalAs(UnmanagedType.Interface)] out System.Object obj);

 

}

No Comments