Use the hwnd (Globals.ThisAddIn.Application.Hwnd) to identify the Excel window. This will work well both for Office2013 (which uses an SDI approach) and older versions of Office that use MDI windows. Here is a class you can use for this:
public class TaskPaneManager
{
static Dictionary<string, CustomTaskPane> _createdPanes = new Dictionary<string, CustomTaskPane>();
/// <summary>
/// Gets the taskpane by name (if exists for current excel window then returns existing instance, otherwise uses taskPaneCreatorFunc to create one).
/// </summary>
/// <param name="taskPaneId">Some string to identify the taskpane</param>
/// <param name="taskPaneTitle">Display title of the taskpane</param>
/// <param name="taskPaneCreatorFunc">The function that will construct the taskpane if one does not already exist in the current Excel window.</param>
public static CustomTaskPane GetTaskPane(string taskPaneId, string taskPaneTitle, Func<UserControl> taskPaneCreatorFunc)
{
string key = string.Format("{0}({1})", taskPaneId, Globals.ThisAddIn.Application.Hwnd);
if (!_createdPanes.ContainsKey(key))
{
var pane = Globals.ThisAddIn.CustomTaskPanes.Add(taskPaneCreatorFunc(), taskPaneTitle);
_createdPanes[key] = pane;
}
return _createdPanes[key];
}
}
Here I'm actually combining the Excel window hwnd and some arbitrary string identifier to identify the taskpane. The idea is to support multiple taskpanes in the same addin.
Here is an example for how to use it from the ribbon:
private void button1_Click(object sender, RibbonControlEventArgs e)
{
var taskpane = TaskPaneManager.GetTaskPane("A", "Task pane type A", () => new UserControl1());
taskpane.Visible = !taskpane.Visible;
}
private void button2_Click(object sender, RibbonControlEventArgs e)
{
var taskpane = TaskPaneManager.GetTaskPane("B", "Task pane type B", () => new UserControl2());
taskpane.Visible = !taskpane.Visible;
}
If you open multiple workbooks in Excel, both Excel window will have their own taspaneA and taskpaneB.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…