在保存excel句柄的同时崩溃

当启动我的Excel加载项时,我使用以下代码保留一个Excel窗口句柄:

ExcelWindow = new NativeWindow(); ExcelWindow.AssignHandle(new IntPtr(Application.Hwnd)); 

说到释放手柄,我试图在closures的时候这样做:

 private void ThisAddInShutdown(object sender, EventArgs e) { try { ExcelWindow.ReleaseHandle(); } catch { } } 

在Debug模式下退出excel时,一切正常。 不幸的是,当在生产系统上运行这个代码时,我发生崩溃,无法debugging正在发生的事情。 我得到一个“窗口正在检查这个问题”窗口,随后消失,就是这样。

这真的不是什么大问题,但我不想用这样的东西来惹恼用户。 那么,有没有人知道它可能是什么,我怎么可以debugging呢? 谢谢。

我的解决scheme

 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 }