Apr 3, 2009

Visual Studio - Writing a simple Add-In (plugin)

An add-in is an extension which integrates with the Visual Studio environment and provides new functionality to it. An add-in has full access to Visual Studio (IDE) tools and APIs and can interact with them. An add-in is a compiled DLL file which can be loaded by Visual Studio when it starts.





Creating a Sample Add-In
1. Create a New → Project
2. Select Other Project Types → Extensibility → Visual Studio Add-in



3. An Add-In wizard pops up which will guide you through a series of 7 steps including the welcome page to configure your add-in









Select for creating a 'Tools' menu item. This will list the add-in in tools menu items







On clicking finish, three main files are generated for you
a) CommandBar.resx (Resource File)
b) Connect.cs (Main class file for Add-In logic)
c) WizardSample.AddIn (XML Configuration file for your add-in)


Build the solution and run the project. You will see a Visual Studio instance running within the visual studio. Click on 'Tools' and you can find your Add-In there.




Modify the function OnConnection() as below to add the plugin to 'MenuBar'


public void OnConnection(object application, ext_ConnectMode connectMode,
object addInInst, ref Array custom)
{

_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
if(connectMode == ext_ConnectMode.ext_cm_UISetup)
{
object []contextGUIDS = new object[] { };
Commands2 commands = (Commands2)_applicationObject.Commands;
CommandBar bar = ((CommandBars)_applicationObject.CommandBars)["MenuBar"];

try{
Command command = commands.AddNamedCommand2(
_addInInstance, "MyAddin1", "Demo", "Do Something", true, 59,
ref contextGUIDS,(int)vsCommandStatus.vsCommandStatusSupported+
(int)vsCommandStatus.vsCommandStatusEnabled,
(int)vsCommandStyle.vsCommandStylePictAndText,
vsCommandControlType.vsCommandControlTypeButton);

//Add a control for the command to the tools menu:

if(command != null) {
command.AddControl(bar, 1);
}
}
catch(System.ArgumentException){
}
}
}






Modify Exec() function to add some functionality to the plugin

public void Exec(string commandName, vsCommandExecOption executeOption,
ref object varIn, ref object varOut, ref bool handled)
{
handled = false;
if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if(commandName == "MyAddin1.Connect.MyAddin1")
{
handled = true;
MessageBox.Show("Hello from Demo AddIn");

return;
}
}
}






No comments :

Post a Comment