I\'m developing a Word 2007-2010 addin using VSTO in Visual Studio 2008. In my addin, I need a custom task pane for each open word document. Basically, I need to create a ta
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::
Maybe you can check "Word.Application.Documents.Count" in the DocumentNew- and DocumentOpen-Event to track the actual open document.
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.
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
}
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.