你可能想通了这一点很久以前,但无论如何:您可以设置从OnConnection
内的事件,如下图所示,这是一个外接的连接类的代码片段(假设你使用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
}
重点在于,要连接您需要的解决方案和项目事件,解决方案或项目已经加载并不重要。它们没有附加到任何特定的解决方案或项目,它们由Visual Studio对象模型提供,并嵌入在EnvDTE命名空间中。
无论如何,做任何事情都没什么意义,因为你可以在VS启动时配置一个加载器来加载,在这种情况下,永远不会有任何加载的解决方案/项目。
有几个渔获,但:
- 这是重要您保持到SolutionEvents类作为您的连接类中的一个成员变量的引用,否则the events will never fire,(see also here)。
- 您需要确保您检查传入
OnConnection
的connectMode
参数。这会被多次调用不同的参数,如果这样做的方式错误,您可能会多次连接事件,这肯定会是一个问题。另外,通常任何Addin IDE,如菜单和其他东西,都是在OnConnection
之内设置的,所以如果你做得不对,你可能会得到重复的菜单项。
下面的几个三分球,提供的一些代码是VB代码,如果你要寻找的是:
最后,这里列出了一系列文章,其中约70%包含关于插件的基本和高级主题:
找到段名为MZ-工具用品系列(关于插件)和看看发生了什么覆盖那里。