代码之家  ›  专栏  ›  技术社区  ›  awj

我应该在visualstudio外接程序中的何处附加解决方案或项目事件?

  •  5
  • awj  · 技术社区  · 15 年前

    有人能建议将解决方案或项目事件(如ProjectAdded)添加到visualstudio外接程序的最佳位置吗?

    如果在外接程序连接时执行此操作,则没有加载解决方案,那么如何判断何时加载了解决方案?

    例如,如果我编写一个事件来处理正在添加的项目项,我应该将其附加到哪里?事件将由项目触发,而解决方案又会触发,因此我无法在外接程序连接时附加事件,因为在外接程序连接时没有解决方案。

    另一方面,如果我在Exec()事件中添加它们,那么我需要做一些检查,比如是否已经附加了该事件,并且我确信在连接事件和Exec()事件之间一定有一种更整洁的方式。

    1 回复  |  直到 15 年前
        1
  •  5
  •   takrl cck    14 年前

    你可能早就知道了,但不管怎样:你可以从内部设置你的事件 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工具文章系列(关于外接程序)

    推荐文章