前言
在上篇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;
}