Logo
HOWTO: Retrieve the Command that created a CommandBarControl from a Visual Studio add-in or macro

Author: Carlos J. Quintero (Microsoft MVP) Applies to: Microsoft Visual Studio .NET 2002
Date: August 2008   Microsoft Visual Studio .NET 2003
Updated: March 2013   Microsoft Visual Studio 2005
      Microsoft Visual Studio 2008
      Microsoft Visual Studio 2010
      Microsoft Visual Studio 2012
Introduction

While most of the time an add-in creates a CommandBarControl from a Command using the Command.AddControl method and therefore it can hold the information that matches them, sometimes it can be needed to retrieve the Command that created a given CommandBarControl without further information.

More Information

The CommandBarControl class lacks a Command property because Visual Studio borrowed the commandbar model from Microsoft Office, which doesn't have the notion of commands (at least externally to the model).

To suply this lack, the automation model (EnvDTE) of Visual Studio provides the EnvDTE.Commands.CommandInfo method, that receives as input a CommandBarControl and have two output parameters to return the Guid and Id of the underlying EnvDTE.Command (commands are actually identified by Guid and Id, while the Name property may not be unique). With the Guid and Id of the command you can call the EnvDTE.Commands.Item method that can receive both values (rather than a single index) and returns the EnvDTE.Command.

The following macro shows the name of the underlying command of the first button on the "Tools" commandbar:

Sub GetCommandFromCommandBarControl()

   Dim iID As Integer
   Dim sGUID As String
   Dim objCommand As Command
   Dim objCommandBarControl As Microsoft.Office.Core.CommandBarControl

   objCommandBarControl = DTE.CommandBars.Item("Tools").Controls(1)

   DTE.Commands.CommandInfo(objCommandBarControl, sGUID, iID)

   objCommand = DTE.Commands.Item(sGUID, iID)
   
   System.Windows.Forms.MessageBox.Show(objCommand.Name)

End Sub

Related articles



Go to the 'Visual Studio Extensibility (VSX)' web site for more articles like this (Articles section)


Top