Jerry Nixon @Work: Word 2007 & VSTO 3/2008 & adding a Custom Task Pane (no, not Custom Actions Pane)

Jerry Nixon on Windows

Friday, December 19, 2008

Word 2007 & VSTO 3/2008 & adding a Custom Task Pane (no, not Custom Actions Pane)

Why didn't the Microsoft Visual Studio Tools for Office 3 for Microsoft Visual Studio 2008 call them Custom Action Panes like Excel? Maybe because they have a knack for naming things. Who knows. But Globals.ThisAddIn.CustomTaskPanes is the collection you'll need.

Document-specific or Global

Because I am using a Word Add In instead of a Document-type project, I should assign the task pane to a specific document - the user might have more than one open and only desire my task pane on the current one.

There should be only one

In a Word Add In, if you add a custom task pane more than once, you actually get more than one task pane! Isn't that amazing? So we will need to first check to make sure the task pane has not already been added.

Choose your own title

When you add a custom task pane you can give it a title. Wonderful. In Excel you're stuck with "document actions" - lame. I talked with the VSTO product team and they confirmed that there's no option to rename it.

Remember task pane orientation

Most Office users and, subsequently, most developers don't even know a task pane can be dragged to other parts of Office - including a horizontal disposition on the bottom or top of the document. Handle it.

Here's the Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Word;
using Microsoft.Office.Tools.Word.Extensions;
using System.Windows.Forms;
using Microsoft.Office.Tools;

public partial class ThisAddIn
{
public void ShowTaskPane()
{
// what word doc gets this task pane?

Microsoft.Office.Interop.Word.Window _Window;
_Window = this.Application.ActiveDocument.ActiveWindow;

// only one per document

foreach (CustomTaskPane _Item in CustomTaskPanes)
if (_Item.Window == _Window)
{
// make sure you can see it

_Item.Visible = true;
return;
}

// what control will we show in the task pane?

UserControl _Control;
_Control = new CustomPanes.Test();

// what will we call our task pane?

string _Title;
_Title = "My Special Title";

// add the task pane

CustomTaskPane _CustomTaskPane;
_CustomTaskPane =
CustomTaskPanes.Add(_Control, _Title, _Window);

// restrict orientation

_CustomTaskPane.DockPositionRestrict =
Microsoft.Office.Core.MsoCTPDockPositionRestrict
.msoCTPDockPositionRestrictNoHorizontal;

// make sure you can see the new task pane

_CustomTaskPane.Visible = true;
}
}