启动Excel加载项时,我使用以下代码保留Excel窗口的句柄:
ExcelWindow = new NativeWindow();
ExcelWindow.AssignHandle(new IntPtr(Application.Hwnd));
在释放手柄时,我尝试在关闭时执行此操作:
private void ThisAddInShutdown(object sender, EventArgs e)
{
try
{
ExcelWindow.ReleaseHandle();
}
catch
{
}
}
在调试模式下退出excel时,一切正常。不幸的是,在生产系统上运行此代码时,我遇到了崩溃,无法调试正在进行的操作。我得到一个'窗口正在检查这个问题'窗口,随后它就消失了,就是这样。
这真的不是什么大问题,但我不想用这样的东西惹恼用户。那么,有没有人知道它可能是什么以及我如何调试它?感谢。
答案 0 :(得分:1)
我的解决方案:
public partial class ThisAddIn
{
ExcelWindow window;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
window = new ExcelWindow();
Application.WorkbookBeforeClose += new Excel.AppEvents_WorkbookBeforeCloseEventHandler(Application_WorkbookBeforeClose);
Application.WorkbookActivate += new Excel.AppEvents_WorkbookActivateEventHandler(Application_WorkbookActivate);
Application.WorkbookDeactivate += new Excel.AppEvents_WorkbookDeactivateEventHandler(Application_WorkbookDeactivate);
}
void Application_WorkbookDeactivate(Excel.Workbook Wb)
{
window.ReleaseHandle();
}
void Application_WorkbookActivate(Excel.Workbook Wb)
{
window.AssignHandle(new IntPtr(Application.Hwnd));
}
void Application_WorkbookBeforeClose(Excel.Workbook Wb, ref bool Cancel)
{
if (Application.Workbooks.Count > 1 || window.Handle == IntPtr.Zero) return;
Cancel = true;
window.ReleaseHandle();
Dispatcher.CurrentDispatcher.BeginInvoke(new MethodInvoker(Application.Quit), null);
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}