本文对Visual Studio 2003的插件编写进行简单介绍,并会在下一篇中介绍如何用开发一个resouce.h的排序器插件。用c++和c#都可以写Visual Studio 2003的插件, c++新建的时候是以COM接口的,而C#则是标准的C#语言接口(?%#^什么叫C#语言接口?)。为了快速上手,我们选择用C#开发。
选择"新建"->"项目"->"其他项目"->"Visual Studio.Net外接程序"创建一个C#的外接项目。默认地,会生成一个Connet.cs文件,该文件就是当你的Visual Studio 启动时加载的东西:
好了,那么具体应该怎么写代码呢,看几个代码片断吧:
1. OnConnection
public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
{
applicationObject = (_DTE)application;
addInInstance = (AddIn)addInInst;
object []contextGUIDS = new object[] { };
// 获得Visual Studio的Commands
Commands commands = applicationObject.Commands;
// 获得Visual Studio的菜单
_CommandBars commandBars = applicationObject.CommandBars;
try
{
// 获得Visual Studio的"工具"菜单
CommandBar toolsBar = (CommandBar)commandBars["Tools"];
foreach(CommandBarControl control in toolsBar.Controls)
{
// 如果VSX菜单已经存在就直接返回
if(control.Caption == "VSX")
{
return;
}
}
// 添加VSX菜单到工具栏下面
CommandBar vsxBar = (CommandBar)commands.AddCommandBar("VSX",vsCommandBarType.vsCommandBarTypeMenu,toolsBar,1);
// 添加OutLook到VSX菜单下面
Command command = commands.AddNamedCommand(addInInstance,"OutLook","打开OutLook","在VS中嵌入OutLook",true,50,ref contextGUIDS,(int)vsCommandStatus.vsCommandStatusSupported+(int)vsCommandStatus.vsCommandStatusEnabled);
command.AddControl(vsxBar,1);
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
看看注释就知道干了些什么。首先获取"工具"菜单,然后在"工具"上面加了个"VSX",
最后在VSX上面加了个"OutLook". F5Debug一下,会弹出Visual Studio 2003,看到工具下面的VSX没有?
不过还没有任何功能。这里要注意的是:command.AddControl(vsxBar,1);就将command命令和vsxBar
绑定在一起了。
2. QueryStatus
public void QueryStatus(string commandName, EnvDTE.vsCommandStatusTextWanted neededText, ref EnvDTE.vsCommandStatus status, ref object commandText)
{
if(neededText == EnvDTE.vsCommandStatusTextWanted.vsCommandStatusTextWantedNone)
{ // 就是上面的OutLook命令
if(commandName == "OutLook")
{
status = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported|vsCommandStatus.vsCommandStatusEnabled;
}
}
}
就是看看菜单的状态罢了,如果commandName == "Outlook",那么是可以执行命令的。
3. Exec
public void Exec(string commandName, EnvDTE.vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
{
if(executeOption == EnvDTE.vsCommandExecOption.vsCommandExecOptionDoDefault && commandName == "OutLook")
{
Process.Start("OutLook.exe");
}
}
当发现执行的命令commandName == "OutLook"时,就调用OutLook.exe进程。就这么简单,Outlook就集成
到Visual Studio2003中了。
最后总结一下:
在Connect.cs中,有下面几个函数需要实现:
OnConnection: 初始化UI的地方,例如将你的菜单"My OutLook"加到"工具"菜单下面。
QueryStatus: 你的菜单("My OutLook")状态。
Exec:是真正调用你插件的地方,例如在Visual Studio中调用Outlook.exe程序。