【问题标题】:C# Excel VSTO add-in - Excel process can't shut down after adding custom task paneC# Excel VSTO 加载项 - 添加自定义任务窗格后 Excel 进程无法关闭
【发布时间】:2017-08-18 19:42:41
【问题描述】:

我正在尝试解决我的 Excel 加载项中的问题,即当我的用户退出 Excel 时 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 无法正常关闭是什么问题?

请指教,谢谢!

【问题讨论】:

  • AFAIK 任务/操作窗格有此类问题的历史记录,您很有可能找不到好的答案。您可以尝试不同的 VSTO 版本和/或 Office 应用程序/版本。 MSDN 论坛可能也有一些东西。

标签: c# excel vsto


【解决方案1】:

这里给出了添加任务窗格的正确方法:https://msdn.microsoft.com/en-us/library/aa942846.aspx,而且与 commandBars 没有关系,因此您可以在关机时删除您的代码。

    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;
    }

【讨论】:

  • 您给出的答案是在任务窗格中使用 WinForms。我需要使用 WPF,因此需要使用 ElementHost。
  • 你之前没有提到过。尝试在 Startup 函数的范围之外声明您的 taskPaneControl。
  • 我在另一个解决方案中遇到了同样的问题:(
【解决方案2】:

我无法告诉你为什么 Excel 在以这种方式添加自定义任务窗格后没有关闭,你需要按照 @Malick 回答 BUT

在我们称为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 用户控件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多