Creating and managing custom task panes for multiple documents in a VSTO Word addin

前提是你 提交于 2019-11-28 07:44:22

This problem is detailed in this MSDN article titled Managing Task Panes in Multiple Word and InfoPath Documents

You have to create a method that removes orphan CTPs (ie those that no longer have windows attached).

I have followed this article and successfully implemented a CustomTaskPane manager that removes the orphans.

This answer in MSDN

Instead of reactively cleaning up orphaned task panes after you open an existing document, you can proactively clean up by calling the following method from the DocumentOpen event handler before you call CreateTaskPaneWrapper. This code loops through each of the custom task panes that belong to the add-in. If the task pane has no associated window, the code removes the task pane from the collection.

private void RemoveOrphanedTaskPanes()
{
    for (int i = Globals.ThisAddIn.CustomTaskPanes.Count; i > 0; i--)
    {
        CustomTaskPanes ctp = Globals.ThisAddIn.CustomTaskPanes[i - 1];
        if (ctp.Window == null)
        {
            this.CustomTaskPanes.Remove(ctp);
        }
    }
}

private void Application_DocumentOpen(Word.Document Doc)
{
    RemoveOrphanedTaskPanes();
    CreateTaskPaneWrapper(document);
}

Some things to try::

  1. Maybe you can check "Word.Application.Documents.Count" in the DocumentNew- and DocumentOpen-Event to track the actual open document.

  2. To find out if a document is already open (maybe relevant for re-open active document), you can use a dictionary of open documents. The key can the unique document name.

  3. Instead of your IsWindowAlive() method you can maybe catch the Disposed-Event as follows

_vstoDocument.Disposed += _vstoDocument_Disposed;

        void _vstoDocument_Disposed(object sender, EventArgs e)
        {
            //Remove from dictionary of open documents 
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!