2017-08-05 69 views
0

我試圖在Excel加載項中解決問題,其中Excel在用戶退出Excel時被卡在進程中。C#Excel VSTO加載項 - Excel進程在添加自定義任務窗格後無法關閉

我注意到問題開始發生在添加一個CustomTaskPane後,然後當我嘗試關閉Excel時,它不會完全退出並保留在任務管理器中。但是,如果在添加CustomTaskPane之前關閉Excel,則Excel會正確關閉。

下面是關於如何添加CustomTaskPane的簡單代碼,它只是一個簡單的空白任務窗格。

private void ThisAddIn_Startup(object sender, System.EventArgs e) 
    { 
     var host = new ElementHost(); 
     host.Dock = DockStyle.Fill; 
     var taskPaneControl = new UserControl(); 
     taskPaneControl.Controls.Add(host); 
     var taskPaneValue = CustomTaskPanes.Add(taskPaneControl, "My TaskPane"); 
     taskPaneValue.Visible = true; 
    } 

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e) 
    { 
     Office.CommandBar taskBar = null; 
     try 
     { 
      taskBar = Application.CommandBars["Task Pane"]; 
      taskBar.Reset(); 
     } 
     finally 
     { 
      if (taskBar != null) 
      { 
       Marshal.ReleaseComObject(taskBar); 
       taskBar = null; 
      } 
     } 
    } 

至於ThisAddIn_Shutdown方法,這個函數是否爲空並不重要,Excel仍然沒有正確關閉。

添加CustomTaskPane後,Excel無法正常關閉的問題是什麼?

請指教,謝謝!

+0

AFAIK任務/訴權ns窗格有這樣的問題的歷史,並且很有可能你找不到一個好的答案。您可以嘗試不同的VSTO版本和/或Office應用程序/版本。 MSDN論壇可能也有。 – Chris

回答

0

添加任務窗格的正確方法如下:https://msdn.microsoft.com/en-us/library/aa942846.aspx,與命令欄沒有關係,因此您可以在關閉時刪除代碼。

private MyUserControl myUserControl1; 
    private Microsoft.Office.Tools.CustomTaskPane myCustomTaskPane; 

    private void ThisAddIn_Startup(object sender, System.EventArgs e) 
    { 
      myUserControl1 = new MyUserControl(); 
      myCustomTaskPane = this.CustomTaskPanes.Add(myUserControl1, "My Task Pane"); 
      myCustomTaskPane.Visible = true; 
    } 
+0

您給出的答案是在任務窗格中使用WinForms。我需要使用WPF,因此需要使用ElementHost。 –

+0

你以前沒有提過它。嘗試在啓動函數的作用域外聲明你的taskPaneControl。 – Malick

+0

我有另一種解決方案,同樣的問題:( –

0

我不能告訴你爲什麼Excel完全相同以這種方式添加自定義taskpane後不敢靠近,你需要遵循@Malick答案,但

在一個新的類,我們將調用UserControlWinForm,將主機添加elementHost1,把你的用戶控件WPF UserControlWpfMain

public class UserControlWinForm : UserControl 
{ 
    public UserControlWinForm() 
    { 
     var elementHost1 = new System.Windows.Forms.Integration.ElementHost(); 
     elementHost1.Dock = DockStyle.Fill; 
     Controls.Add(elementHost1); 
     var frm = new UserControlWpfMain(); 
     elementHost1.Child = frm; 
    } 
} 

而且,以下@Malick,你把你的WinForm的用戶控件

相關問題