Visual Studio 2008可扩展性开发(三):Add-In运行机制解析(下)2011-04-05 博客园 Anders Cui前言在上篇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事件演示
/// <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;
}