This is the first of a series of posts on Visual Studio Add-Ins, that I’m writing to record my experiences on creating a plugin for Visual Studio.
When developing a Visual Studio 2010 addin recently, I was wanting to add an item to the ‘Tools’ menu and to the context menu for the code-editor window.
This article is working from the assumption that you have already created the appropriate Visual Studio AddIns project. If not, you can do so by clicking File -> New Project -> Other Project Types -> Extensibility -> Visual Studio Add-in, and following the setup wizard.
The project you are given should add the menu items to the ‘Tools’ menu by default.
public void OnConnection(....
CommandBar menuBarCmds = ((CommandBars)_applicationObject.CommandBars)["MenuBar"];
CommandBarControl toolsControl = menuBarCmds.Controls["Tools"];
CommandBarPopup toolsPopup = (CommandBarPopup)toolsControl;
Command command = commands.Aon ddNamedCommand2(_addInInstance, ....
And to execute, we add our desired code to the Exec method later:
public void Exec(....
if(commandName == "MyAddin1.Connect.MyAddin1")
//your code here
The code above adds a new option to the ‘Tools’ menu under ‘Menu Bar’. We are wanting to add specifically to the code editor context menu but are not sure which one it is.
I tracked this down rather unscientifically using the following process.
Firstly, add the following code to the OnConnection method:
CommandBars AllCommandBars = (CommandBars)_applicationObject.CommandBars;
We really want to inspect the contents of this object, and there is no better place than in debug mode. So, place a breakpoint upon this line and launch the app.
When the debugger hits the breakpoint you can step over the line (F10) and then inspect the contents:
As we can see there are 465 possible menus that we could add our item to. Which one? Well, it’s not “Code Window” as I originally anticipated. So how do we find this?
You may have a better method, but the way I found it was by trial and error.
I added the new menu item to all (465) menu controls in visual studio with the following loop
foreach (CommandBar cc in cmdBars)
if (cc.Index >= 1 && cc.Index <= 465)
I then narrowed this using a divide and conquer technique by adjusting the bounds of the loop:
if (cc.Index >= 1 && cc.Index <= 256)
if (cc.Index >= 1 && cc.Index <= 128)
if (cc.Index >= 64 && cc.Index <= 128)
Until I eventually found what I was looking for.
Of worthy note (amongst others) are these other types of editor file:
- HTML Context
- ASPX Context
- ASPX Code Context
- ASPX VB Code Context
Next - Visual Studio Add Ins – Changing The Default Icon