Add-In运行机制解析(下)
在上篇Add-In运行机制解析(上)中,我分析了Add-In向导生成的代码,从中我们知道只要创建一个类库,它包含实现了IDTExtensibility2接口的类,然后为其建立.addin配置文件,就可以实现一个Add-In了。本文将更进一步,介绍Add-In的事件和生命周期,为今后的开发打下基础。
Add-In的事件
Add-In是事件驱动的,可以猜到的事件有加载、卸载、状态改变等等。事实上,这些事件都与IDTExtensibility2接口有关,也就是该接口的5个方法:
如果要了解这些方法如何执行,一个办法是在这些方法中加一个MessageBox,然后通过Add-In Manager进行一些操作,来观察事件的执行。现在使用Add-In向导建立一个简单的Add-In,名字为LifeCycleAddin,不要选择在Tools菜单显示命令,也不要选择在VS启动时加载。然后把Connect类的代码简化一下:
C# Code - Add-In事件演示
双击代码全选123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899/// <summary>The object for implementing an Add-in.</summary> ??public class Connect : IDTExtensibility2 ??{ ?? public Connect() ?? { ?? } ???? /// <summary> ?? /// Receives notification that the Add-in is being loaded. ?? /// </summary> ?? public void OnConnection(object application, ext_ConnectMode connectMode,? ?? object addInInst, ref Array custom) ?? { ?? _applicationObject = (DTE2)application; ?? _addInInstance = (AddIn)addInInst; ???? MessageBox.Show(string.Format("Event: OnConnection, connectMode: {0}", connectMode)); ?? } ???? /// <summary> ?? /// Receives notification that the Add-in is being unloaded. ?? /// </summary> ?? public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom) ?? { ?? MessageBox.Show(string.Format("Event: OnDisconnection, connectMode: {0}", disconnectMode)); ?? } ???? /// <summary> ?? /// Receives notification when the collection of Add-ins has changed. ?? /// </summary> ?? public void OnAddInsUpdate(ref Array custom) ?? { ?? MessageBox.Show("OnAddInsUpdate"); ?? } ???? /// <summary> ?? /// Receives notification that the host application has completed loading. ?? /// </summary> ?? public void OnStartupComplete(ref Array custom) ?? { ?? MessageBox.Show("OnStartupComplete"); ?? } ???? /// <summary> ?? /// Receives notification that the host application is being unloaded. ?? /// </summary> ?? public void OnBeginShutdown(ref Array custom) ?? { ?? MessageBox.Show("OnBeginShutdown"); ?? } ?? private DTE2 _applicationObject; ?? private AddIn _addInInstance; ??}每个方法的注释说明了相应的事件何时触发。OnConnection是在Add-In加载的时候;OnDisconnection是在Add-In卸载的时候;OnAddInsUpdate是在所有Add-In的集合状态发生改变的时候;OnStartupComplete是在宿主环境加载完成的时候;OnBeginShutdown则是在宿主环境将被关闭的时候。现在编译项目,然后关闭VS。
打开VS,开始第一回合的观察。由于没有选择在VS启动时加载,所以现在什么也不会发生。打开Add-In Manager,对于LifeCycleAddin,将其设置为可用,确定。这时触发了OnConnection,connectMode为ext_cm_AfterStartup,也就是说在VS启动之后才加载的;然后还触发了OnAddinsUpdate,因为LifeCycleAddin的状态改变了。再次打开Add-In Manager,对于LifeCycleAddin,将其设置为启动时加载,确定,再次触发OnAddinsUpdate。现在关闭VS,由于Add-In已经加载,所以会触发OnBeginShutdown,然后是OnDisconnection,说明Add-In已经被卸载。