2017-08-05 71 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的用户控件

相关问题