共用方式為


Creating Custom Task Panes in the 2007 Office System

Summary: The 2007 release of the Microsoft Office system introduces custom task panes that give you the tools to put the features and information your customers need when and where they want them. Learn how you can use custom task panes in your applications. (14 printed pages)

Mark O'Hara, Microsoft Corporation

Frank Rice, Microsoft Corporation

September 2006

Applies to: 2007 Microsoft Office Suites, Microsoft Office Access 2007, Microsoft Office Excel 2007, Microsoft Office InfoPath 2007, Microsoft Office Outlook 2007, Microsoft Office PowerPoint 2007, Microsoft Office Word 2007

Contents

  • Introducing Custom Task Panes

  • Creating a Flexible User Experience

  • Custom Task Pane Scenarios

  • How Custom Task Panes Work

  • Creating Custom Task Panes as COM Add-Ins

  • Conclusion

  • Additional Resources

Introducing Custom Task Panes

The 2007 release of the Microsoft Office system introduces a programmable custom task pane that changes the way you develop solutions for documents in the 2007 release of the Microsoft Office system. This article explores the task pane and discusses solutions and scenarios using the task pane.

The following products can implement custom task panes:

  • Microsoft Office Access 2007

  • Microsoft Office Excel 2007

  • Microsoft Office InfoPath 2007

  • Microsoft Office Outlook 2007

  • Microsoft Office PowerPoint 2007

  • Microsoft Office Word 2007

You can create custom task panes in any language that supports COM and that enables you to create dynamic-linked library (DLL) files, for example, Microsoft Visual Basic 6.0, Microsoft Visual Basic .NET, Microsoft Visual C++, Microsoft Visual C++ .NET, and Microsoft Visual C. However, Microsoft Visual Basic for Applications (VBA) does not support creating custom task panes. Custom task panes use other technologies with which you are already familiar, for example, Microsoft ActiveX controls.

Creating a Flexible User Experience

Task panes, introduced in Microsoft Office XP, enable users to add and manipulate content in their documents. For example, users can query and insert information from external sources into their documents, add rich graphics, format a document, insert structured XML data using extensible schema definition (XSD) files, and complete many other tasks using task panes.

In the 2007 release of Office, improved task panes provide an easy, flexible way for you to create and deploy application-specific functionality in fully customizable task panes that users can dock to different areas of the screen. Users can display multiple custom task panes when they need them and control each one individually. Because custom task panes are deployed as Component Object Model (COM) add-ins, you can add controls such as standard buttons to the new 2007 Office Fluent user interface to allow users to display the task panes.

Custom Task Pane Scenarios

Here are just a few example scenarios that use custom task panes:

  • At the fictitious company Fabrikam Corporation, employees save documents according to the document's subject matter. For example, if an employee creates a sales report in Office Excel 2007, then the employee saves the file onto a network server that stores sales report information. Although this enables managers to find the information easily, employees must manually look up the server information.

    Nicole, an analyst and light tool developer at Fabrikam, thinks that there is a better way to help employees discover this information. She decides to use a custom task pane. Because Nicole has created and deployed COM add-ins in the past, she is familiar with the process. She creates a custom ActiveX control, inserted in a Microsoft Windows Form, that contains a drop-down control and a button. The drop-down box helps the user quickly find the right server.

    NoteNote

    Windows Forms is the development library within the Microsoft .NET Framework for building rich Microsoft Windows–based applications.

    After the user finishes the document, he displays Nicole's task pane, selects the appropriate server, and then clicks Save. Because users no longer need to look up server information manually, they are more productive and relieved from a tedious task.

  • Chris, a third-party developer at the fictitious company Contoso Incorporated, wants to integrate and expose content currently stored in a content management server. He wants to make this content available in a way that does not interfere with the way his customers work. After some investigation, he decides to develop a custom task pane in managed code using tools in Visual Studio Tools for the Microsoft Office System (Visual Studio Tools for Office). He uses Visual Studio Tools for Office version 3.0 to add the ActiveX control because he is familiar with its tools. He also provides easy access to his custom task pane by adding buttons to the 2007 Office Fluent Ribbon. The Ribbon gives the user control over when to display the task pane. He digitally signs the add-in and ActiveX controls, and then packages and deploys the custom task pane to each department.

    NoteNote

    Visual Studio Tools for Office version 3.0 is not available for Beta 2.

  • Jan wants to develop a solution with custom task panes that she can sell and make available for customers as a downloadable sample from the Web. Using the existing custom task pane infrastructure, Jan easily creates a COM add-in and ActiveX control that she packages as a downloadable sample on the Internet. For added security, she digitally signs the add-in and control, and then deploys the package to a Web server.

How Custom Task Panes Work

You create custom task panes using COM add-ins in either managed or unmanaged code. In addition to the IDTExtensibility2 interface that is required of all COM add-ins, the COM add-in for the custom task pane must implement the ICustomTaskPaneConsumer interface, which exposes the CTPFactoryAvailable method. The syntax for this method is:

Microsoft.Office.Core.ICustomTaskPaneConsumer.CTPFactoryAvailable (Microsoft.Office.Core.ICTPFactory CTPFactoryInst)

The ICTPFactory interface exposes the CreateCTP method. The syntax for this method is:

Microsoft.Office.Core.ICTPFactory.CreateCTP (string CTPAxID, string CTPTitle, [Optional] object CTPParentWindow) As CustomTaskPane

Creating a custom task pane is straightforward. First, you create a custom ActiveX control project with a Windows Form and other ActiveX controls. The Windows Form and controls represent the interface your users see.

NoteNote

If you use Windows Forms in your ActiveX control, you also need to have Microsoft .NET Framework 2.0 installed. If you create your ActiveX control in unmanaged code, there is no requirement for the .NET Framework.

You may be able to use pre-built ActiveX controls that you purchase or download from the Web. However, pre-built controls can have limits, for example, an inability to repaint the screen after changes in height or width. You can experiment to determine if a pre-built control is compatible with custom task panes.

Next, you create the COM add-in that invokes the Windows Form. The add-in contains the code to create the custom task pane. The add-in can be loaded at various points:

  • When the application starts

  • When the user explicitly loads it through the COM Add-ins dialog box

  • On demand, for example, when the user clicks a custom toolbar button

During loading, the application calls the CTPFactoryAvailable method. This method passes an instance of the CTPFactory object, which, in turn, exposes the CreateCTP method through the ICTPFactory interface. CreateCTP takes the class ID (CLSID) or program ID (ProgID) of the ActiveX control. CreateCTP returns a CustomTaskPane object representing a single custom task pane. This instance of the CustomTaskPane object stays in memory until the add-in calls the CustomTaskPane.Delete method or until the add-in is disconnected. After creating the task pane, you must explicitly make it visible by setting the Visible property to True.

The task pane stays visible until you explicitly dismiss it, until you set the Visible property of the CustomTaskPane object to False, or until you call the Delete method of the CustomTaskPane object.

Optionally, CreateCTP accepts a Window object argument, CTPParentWindow. The add-in uses this argument to specify a document window in which to host the task pane. In most cases, setting this argument ties the task pane to a specific document. If this argument is not present, the add-in creates the CustomTaskPane object in the host application's active window. You type this parameter as an Object (a Variant in C++) because the object passed in differs depending on the host application:

  • In Word, a Window object

  • In Excel, a Window object

  • In PowerPoint, a DocumentWindow object

  • In InfoPath, a Window object

  • In Outlook, an Inspector object or an Explorer object

Theoretically, you can create any number of custom task panes. Only screen space and memory restrictions limit the number of panes. However, to minimize restrictions, release the CTPFactory instance and any task panes created during that instance in your shutdown code. You can do this during the OnDisconnection event or the OnBeginShutdown event of the IDTExtensibility2 interface.

A CustomTaskPane object represents a single task pane frame. The following table shows the methods, properties, and events for this object.

Table 1. Settings for the CustomTaskPane object

Member Type

Name

Type

Notes

Property

Application

Object

Read-only. Application object of the host application.

Property

Window

Object

Read-only. Parent Window object. The type depends on the host application.

Property

Visible

Boolean

Controls visibility in the user interface.

Property

ContentControl

Object

Read-only. The ActiveX control instance displayed in the custom task pane frame. This property is automatically set when CreateCTP is called.

Property

Title

LPSTR

Read-only. The title displayed for the task pane. This property is automatically set when CreateCTP is called. This is the default property for the user interface.

Property

DockPosition

MsoCTPDockPosition

Specifies Right, Left, Top, Bottom, or Floating. The default is Right when using a right-to-left UI language and Left if you are using a left-to-right language.

Property

DockPositionRestrict

MsoCTPDockPositionRestrict

Specifies a restriction on the orientation of a custom task pane, for example, horizontal or vertical. The default is None.

Method

Delete

 

Deletes the task pane, which also frees the ActiveX control instance.

Event

VisibleStateChange

 

Occurs when the Visible property changes. You can check its value to determine the new state.

Event

DockPositionStateChange

 

Occurs when the DockPosition property changes. You can check its value to determine the new state.

Enumeration

MsoCTPDockPosition

 

msoCTPDockPositionLeft = 0,msoCTPDockPositionTop = 1,msoCTPDockPositionRight = 2,msoCTPDockPositionBottom = 3,msoCTPDockPositionFloating = 4

Enumeration

MsoCTPDockPositionRestrict

 

msoCTPDockPositionRestrictNone = 0,msoCTPDockPositionRestrictNoChange = 1msoCTPDockPositionRestrictNoHorizontal = 2,msoCTPDockPositionRestrictNoVertical = 3

Creating Custom Task Panes as COM Add-Ins

In the following sections, you create a simple, custom task pane for Office Word 2007. The task pane enables users to add text to a text box, and then click a button to populate the document at the current cursor position.

You create the custom task pane from a COM add-in and an ActiveX control. Most of the work to create the custom task pane occurs in the add-in; the ActiveX control just hosts the user interface. You develop the task pane using managed code written in Visual C.

Creating Custom Task Panes with Visual C#

In this section, you create the ActiveX control for the custom task pane. The control consists of a form that contains a label, a text box, and a button.

Figure 1. Custom task pane sample in Word

Custom task pane sample in Word

This is the general process (described in more detail in the following sections) to create an ActiveX control for the custom task pane:

  1. Create a Visual C# Windows Control Library project.

  2. Insert a form, and then add a label, text box, and button control.

  3. Add a public interface to the project that notifies the COM add-in when the button is clicked.

  4. Add code to the control class to implement the interface.

  5. Test the project.

Creating the Windows Control Library Project

Using the steps in this section, create the ActiveX control to insert into the custom task pane.

To create a Windows control library project

  1. Start Microsoft Visual Studio 2005.

  2. On the File menu, click New Project.

  3. In the New Project dialog box, select the Windows Control Library project template from the list of Visual C# Projects. Type SampleActiveX in the Name box and click OK.

  4. In Solution Explorer, right-click UserControl1.cs, and then select View Code.

  5. In Solution Explorer, right-click the project SampleActiveX, and then click Properties.

  6. In the SampleActiveX tab, click Build and select the Register for COM interop check box.

  7. Right-click the SampleActiveX tab, and then click Close.

  8. From the File menu, choose Save All. In the Save Project dialog box, click the Save button.

    The following steps add a reference to the Microsoft Office 12 Object Library and to the Primary Interop Assemblies in Office Word 2007:

  9. In Solution Explorer, right-click the References node, and then click Add Reference.

  10. Click the COM tab, and then scroll downward to Microsoft Office 12.0 Object Library and click OK.

  11. The new references appear under the References node in Solution Explorer.

The project is now ready for you to add controls to the form.

Adding Windows Controls to the Custom Control

In this section, add controls to the control that you created in the previous section.

To add controls to the form designer

  1. If the designer is not already displayed, in Solution Explorer, click UserControl1.cs and then click View Designer.

  2. On the View menu, click Toolbox.

  3. On the Common Controls tab of the toolbox, add the controls in Table 2 to the work surface, and then set their properties.

    Table 2. Windows Forms controls for the custom control

    Control Type

    Text Property

    Name Property

    Label

    Enter text

    label1

    Text Box

    blank

    txtInputText

    Button

    Click to insert

    btnInsert

  4. Click the text box, and then, in the Property window, set the Multiline property to True.

Adding Code to the Project

Next, add code that implements the event handlers, to give the controls functionality.

To implement the button click event handler and initialize the UserControl1 class

  1. If the code window is not already displayed, in Solution Explorer, right-click UserControl1.cs and click View Code.

  2. Locate the namespace SampleActiveX statement, and then add the following lines above it:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    using System.IO;
    

    These statements create aliases for the namespace and import types defined in other namespaces.

  3. After the open brace, just below the namespace SampleActiveX statement, add the following code:

    public interface SampleActiveXControlInterface
    {
       event InsertTextEventHandler InsertTextClicked;
    }
    [ComVisible(true)]
    

    The ActiveX control has a public interface, SampleActiveXControlInterface, with a single event, InsertTextClicked, to notify the add-in when the user clicks the button. You can include additional events, methods, or objects that your add-in requires here.

  4. Specify that the myControl class implements the SampleActiveXControlInterface interface by replacing the public partial class UserControl1 : UserControl statement with the following code:

    public partial class myControl : System.Windows.Forms.UserControl, SampleActiveXControlInterface
    
  5. Replace the public UserControl1() statement with the following code:

    public event InsertTextEventHandler InsertTextClicked;
    
    public myControl()
    {
       // This call is required by the Form Designer in Windows.Forms.
       InitializeComponent();
    
       btnInsert.Click += new EventHandler(btnInsert_Click);
    }
    

    Next, this code initializes the control and sets up the event handler for the button.

  6. Below the closing brace of the public myControl routine, add the event handler for the button:

    private void btnInsert_Click(object sender, EventArgs e)
    {
       string textBoxText = this. txtInputText.Text;
       this.InsertTextClicked(this, textBoxText);
    }
    
  7. Just below the procedure that you added in the previous step, add the following code:

    public delegate void InsertTextEventHandler(object sender, string insertTextArgs);
    

    This code defines a delegate for the button's event handler that the add-in project uses.

  8. On the File menu, click Save All, and then click Close Project.

    Next, you need to register the ActiveX control.

  9. Open a Command Prompt window: click Start, point to AllPrograms, point to Accessories, and then click Command Prompt.

  10. In the Command Prompt window, type:

    "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\regasm" /codebase "C:\path to your project\SampleActiveX.dll"

Creating Shared Add-ins for Custom Task Panes

You use the Shared Add-in Wizard in Visual Studio 2005 to create an add-in that builds the custom task pane when loaded.

The shared add-in that Visual Studio 2005 creates is a .NET assembly with the extension .dll. Although it is not a COM DLL, Visual Studio 2005 adds enough information to mimic a COM add-in when applications in the 2007 Office release load the add-in at run time.

  1. On the File menu, click New Project.

  2. Create a new Shared Add-In project.

    You can find this project type by clicking Other Project Types in the Project types pane, and then clicking Extensibility.

  3. Type SampleCTPAddin in the Name box, and then click OK.

  4. In the Shared Add-in Wizard, click Next on the Welcome to the Add-in Wizard page.

  5. On the Select a Programming Language panel, select Create an Add-in using Visual C.

  6. On the Select an Application Host page, clear all of the check boxes except Microsoft Word, and then click Next.

    This specifies the application that runs the add-in after you create it.

  7. On the Enter a Name and Description page, type Sample CTP Addin for the name of the add-in. Clear the description box and then click Next.

    This name displays in the Available Add-Ins list of the Add-In Manager dialog box. It informs users what the add-in does, how it works, and other relevant information.

  8. In the Choose Add-In Options panel, select the I would like my Add-in to load when the host application loads check box, and then click Next.

  9. Choose Finish to create the add-in.

The Shared Add-in Wizard automatically registers the add-in with Microsoft Windows on your development computer.

Note

You can manually register the add-in using the Regasm.exe file provided by .NET Framework version 2.0. Using the default location, type the following command in a Command Prompt window: "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\regasm" /codebase "C:\path to your project\SampleCTPAddin.dll"

Adding Functionality to Add-Ins

Adding the following procedures to the SampleCTPAddin project makes your add-in useful by setting its behavior when it is loaded and unloaded, which occurs when Office Word 2007 starts and is shutdown. The procedures also create an instance of the task pane and add the code that makes the button functional.

To add a reference to the Microsoft Office 12 Object Library and to the primary interop assemblies in Word 2007

  1. In the Solution Explorer, right-click the References node, and then click Add Reference.

  2. In the Add Reference dialog box, click the .NET tab.

  3. Scroll and select Microsoft.Office.Interop.Word, and then click OK.

  4. Again display the Add Reference dialog box. On the COM tab, scroll to Microsoft Office 12.0 Object Library, select it, and then click OK.

  5. The project uses the MessageBox object to report status as the add-in loads and unloads. If it does not already exist, you need to set a reference to the System.Windows.Forms namespace on the .NET tab of the Add Reference dialog box, using the procedures described previously.

    The new references appear under the References node of the project.

  6. In Solution Explorer, right-click Connect.cs, and then click View Code.

  7. Below the namespace SampleCTPAddin statement, add the following code:

    using System;
    using Microsoft.Office.Core;
    using Extensibility;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    using SampleActiveX;
    using WordPia = Microsoft.Office.Interop.Word;
    
  8. At the end of the public class Connect : statement, past Extensibility.IDTExtensibility2, type a comma and ICustomTaskPaneConsumer.

    The ICustomTaskPaneInterface interface has one method, CTPFactoryAvailable, which returns an instance of the CTPFactory object for the host application.

    NoteNote

    Earlier in the project, you added a reference to the host application's object. The OnConnection method sets the applicationObject object to the instance of Office Word 2007 that hosts the custom task pane. This gives the add-in full access to the object model in Office Word 2007.

  9. Just below the public class Connect() statement, add the following code to create an object that points to the UserControl1 class, and to create a variable for the primary interop assemblies in Office Word 2007:

    private myControl sampleAX = null;
    private WordPia.Application applicationObject;
    
  10. In the OnConnection procedure, replace the statements with this code:

    applicationObject = (WordPia.Application)application;
    addInInstance = addInInst;
    
    MessageBox.Show("SampleCTPAddin is loaded.");
    

    The MessageBox statement assures you that the add-in loads successfully in Office Word 2007.

  11. In the OnBeginShutDown procedure, add the following code:

    MessageBox.Show("SampleCTPAddin is unloading.");
    
  12. Scroll downward until you see the private object applicationObject; statement, and then delete it.

  13. After the private object addInInstance; statement, add the following code, which implements the CTPFactoryAvailable method of the ICustomTaskPaneConsumer interface and returns a CTPFactoryInst object.

    region ICustomTaskPaneConsumer Members
    
    object missing = Type.Missing;
    public CustomTaskPane CTP = null;
    
    public void CTPFactoryAvailable(ICTPFactory CTPFactoryInst)
    {
       CTP = CTPFactoryInst.CreateCTP("SampleActiveX.myControl", "Task Pane Example", missing);   
       sampleAX = (myControl)CTP.ContentControl;
       sampleAX.InsertTextClicked += new InsertTextEventHandler(sampleAX_InsertTextClicked);
       CTP.Visible = true;
    }
    
    endregion
    

    The code calls the CreateCTP method of the CTPFactoryInst object to create a new Custom Task Pane object. The object has the SimpleActiveX control referenced by its ProgId value. Although this creates the custom task pane, the task pane is not visible until you set the CTP.Visible property to True.

    The add-in uses a reference to the SampleActiveX control, and the following code sets the sampleAX object to the ActiveX control:

       sampleAX = (myControl) CTP.ContentControl;
    
  14. Add the following code, which inserts the text into the document when the user clicks the button:

    private void sampleAX_InsertTextClicked(object sender, string insertTextArgs)
    {
       WordPia.Range myRange = null;
       myRange = applicationObject.ActiveDocument.Content;
       myRange.InsertAfter(insertTextArgs);
    }
    

To build and test the add-in

  1. On the File menu, choose Save All to save the project.

  2. On the Build menu, click Build Solution.

    If you are able to compile the project with no build errors, the code automatically adds the add-in to the registry at this location:

    HKLM\Software\Microsoft\Office\Word\Addins\SampleCTPAddin.Connect
    

    If the add-in does not load when you start Office Word 2007, check for the existence of this registry key. Within the key, you should see a DWORD named LoadBehavior with a value of 0x0000003(3). If you don't see the DWord, add the SampleCTPAddin.Connect key to the Addins folder and then add a LoadBehavior DWord and modify its value to 3.

    Important noteImportant

    Before modifying the registry, create a backup. Additionally, be sure that you know how to restore the registry if a problem occurs. For more information about how to back up, restore, and modify the registry, see the Microsoft Knowledge Base article entitled Description of the Microsoft Windows registry.

  3. To test the add-in, start Word 2007.

  4. When you see a message that SampleCTPAddin is loading, click OK.

  5. When you see the Task Pane Example task pane docked on the right side of the active window, click inside the text box, and then type some text.

  6. Click the Click to insert button to insert the text that you typed into the document at the selection point.

  7. Drag the task pane to another side of the active window.

Conclusion

Task panes have been an important feature of Microsoft Office since they were introduced in Office XP. Task panes replace many dialog boxes that can be hard to find and that are often cluttered with options that may not be relevant for the current task. Custom task panes in the 2007 release of the Microsoft Office system put relevant features where users can find them, when they need them. Custom task panes provide a customizable way to give your users more functionality without taking up valuable workspace. Custom task panes are an important addition to an Office developer's toolbox.

Additional Resources

For more information about creating custom applications to display content and controls, see the following resources. Although these articles are specific to Office XP, they are still relevant for the 2007 release of the Microsoft Office system.