我在编写 Excel 插件时解决了类似的问题。不需要 dll 导入。我使用 System.Windows.Forms.NativeWindow 类解决了这个问题。
起初,我创建了我自己的类继承自 NativeWindow 类,并在其中声明了两个事件 Activated 和 Deactivate,最后重写了 WndProc() 方法以在将消息 WM_ACTIVATE 传递给 WndProc 方法时引发这些事件。根据“消息”参数 WParm 是激活还是停用 Excel 窗口。
public class ExcelWindow: NativeWindow
{
public const int WM_ACTIVATED = 0x0006;
public ExcelWindow():base(){}
//events
public event EventHandler Activated;
public event EventHandler Deactivate;
//catching windows messages
protected override void WndProc(ref Message m)
{
if (m.Msg== WM_ACTIVATED)
{
if (m.WParam.ToInt32() == 1)
{
//raise activated event
if (Activated!=null)
{
Activated(this, new EventArgs());
}
}
else if (m.WParam.ToInt32() == 0)
{
//raise deactivated event
if (Deactivate!=null)
{
Deactivate(this, new EventArgs());
}
}
}
base.WndProc(ref m);
}
}
然后我在我的插件类字段“ExcelWindow myExcelWindow”中创建并将以下代码添加到我的插件的 OnConnection 方法中:
ExcelWindow myExcelWindow;
void Extensibility.IDTExtensibility2.OnConnection(object application, Extensibility.ext_ConnectMode ConnectMode, object AddInInst, ref Array custom)
{
excel = application as Excel.Application;
myExcelWindow = new ExcelWindow();
myExcelWindow.AssignHandle(new IntPtr(excel.Hwnd));
myExcelWindow.Activated += new EventHandler(myExcelWindow_Activated);
myExcelWindow.Deactivate += new EventHandler(myExcelWindow_Deactivate);
//addin code here
}
void myExcelWindow_Activated(object sender, EventArgs e)
{
//do some stuff here
}
void myExcelWindow_Deactivate(object sender, EventArgs e)
{
//do some stuff here
}
我希望这能帮到您。