你可能早就知道了,但不管怎样:你可以从内部设置你的事件
OnConnection
如下所示,这是一个Addin的Connect类的片段(假设您使用的是c#):
using System;
using System.Globalization;
using System.Reflection;
using System.Resources;
using EnvDTE;
using EnvDTE80;
using Extensibility;
using Microsoft.VisualStudio.CommandBars;
namespace MyAddin1
{
/// <summary>The object for implementing an Add-in.</summary>
/// <seealso class='IDTExtensibility2' />
public class Connect : IDTExtensibility2, IDTCommandTarget
{
private DTE2 _applicationObject;
private AddIn _addInInstance;
private SolutionEvents _solutionEvents;
public void OnConnection(object application, ext_ConnectMode connectMode,
object addInInst, ref Array custom)
{
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
// check the value of connectMode here, depending on your scenario
if(connectMode == ...)
SetupEvents();
}
private void SetupEvents()
{
// this is important ...
_solutionEvents = _applicationObject.Events.SolutionEvents;
// wire up the events you need
_solutionEvents.Opened += new _dispSolutionEvents_OpenedEventHandler(_solutionEvents_Opened);
_solutionEvents.AfterClosing += new _dispSolutionEvents_AfterClosingEventHandler(_solutionEvents_AfterClosing);
_solutionEvents.ProjectAdded += new _dispSolutionEvents_ProjectAddedEventHandler(_solutionEvents_ProjectAdded);
}
// add procedures to handle the events here, plus any other
// handling you need, ie. OnDisconnection and friends
}
主要的一点是,要连接您需要的解决方案和项目事件,是否已经加载了解决方案或项目并不重要。它们不是附加到任何特定的解决方案或项目,而是由visualstudio对象模型提供的,并且嵌入到
EnvDTE
命名空间。
不管怎样,做任何其他事情都没有多大意义,因为您可以配置一个加载项在VS启动时加载,在这种情况下,永远不会加载任何解决方案/项目。
不过有几个陷阱:
-
它是
在connect类中保留对SolutionEvents类的引用作为成员变量,否则
the events will never fire
, (
see also here
-
你得检查一下
connectMode
传入的参数
连接
. 它会用不同的参数多次调用,如果用错误的方法调用,可能会多次连接事件,这肯定是个问题。此外,通常任何加载项IDE(如菜单和其他内容)都是从内部设置的
连接
这里有一些提示,提供的一些代码是VB代码,以防您需要:
最后,这里是一个文章列表,大约70%的文章涵盖了有关加载项的基本和高级主题:
找到标题为
MZ工具文章系列(关于外接程序)