2

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

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

在释放手柄时,我尝试在关闭时这样做:

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

  }
}

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

这真的没什么大不了的,但我不想用这样的东西来惹恼用户。那么,有谁知道它可能是什么以及我如何调试它?谢谢。

4

1 回答 1

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
}
于 2013-04-29T13:10:28.190 回答