Visual Studio CommandBars don’t have unique names

Just in case you are not aware of this yet (I found a problem related to this today in the MSDN forum), Visual Studio CommandBars don’t have unique names, which means that retrieving a specific commandbar such as “Project” with this code can fail returning a commandbar that you didn’t expect:

DTE.CommandBars.Item("Project")

In fact, there are 3 or 4 commandbar named “Project” in Visual Studio 2005 and 2008, as this macro will show:

Dim sMsg As String

For Each objCommandBar As CommandBar In CType(DTE.CommandBars, Microsoft.VisualStudio.CommandBars.CommandBars)

   If objCommandBar.Name = "Project" Then
      sMsg = ""

      For Each objCommandBarControl As CommandBarControl In objCommandBar.Controls
         sMsg &= objCommandBarControl.Caption & Microsoft.VisualBasic.ControlChars.CrLf
      Next
      MessageBox.Show(sMsg)

   End If

Next

The same happen with the “View” commandbar and others.

CommandBars are truly identified by Guid/Id pairs, and Dr.eX posted the workaround to this problem some time ago:

Using IVsProfferCommands to retrieve a Visual Studio CommandBar
http://blogs.msdn.com/dr._ex/archive/2007/04/17/using-ivsproffercommands-to-retrieve-a-visual-studio-commandbar.aspx