2

Excelアドインを起動するとき、次のコードを使用してExcelウィンドウへのハンドルを保持します。

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

ハンドルを解放することになると、私はシャットダウンしながらそれをやろうとします:

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

  }
}

デバッグモードでExcelを終了すると、すべてが正常に機能します。残念ながら、本番システムでこのコードを実行すると、何が起こっているのかをデバッグする機能がなく、クラッシュします。「ウィンドウがこの問題をチェックしています」ウィンドウが表示され、その後消えます。それだけです。

それほど大したことではありませんが、このようなことでユーザーを困らせたくはありません。それで、誰かがそれが何である可能性があり、私がこれをどのようにデバッグできるかについて何か考えがありますか?ありがとう。

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 に答える