Поделиться через


Walkthrough: Display custom task panes with email messages in Outlook

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

This walkthrough demonstrates how to display a unique instance of a custom task pane with each email message that is created or opened. Users can display or hide the custom task pane by using a button on the Ribbon of each e-mail message.

Applies to: The information in this topic applies to VSTO Add-in projects for Outlook. For more information, see Features available by Office application and project type.

To display a custom task pane with multiple Explorer or Inspector windows, you must create an instance of the custom task pane for every window that is opened. For more information about the behavior of custom task panes in Outlook windows, see Custom task panes.

Note

This walkthrough presents the VSTO Add-in code in small sections to make it easier to discuss the logic behind the code.

This walkthrough illustrates the following tasks:

  • Designing the user interface (UI) of the custom task pane.

  • Creating a custom Ribbon UI.

  • Displaying the custom Ribbon UI with email messages.

  • Creating a class to manage Inspector windows and custom task panes.

  • Initializing and cleaning up resources used by the VSTO Add-in.

  • Synchronizing the Ribbon toggle button with the custom task pane.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Personalize the Visual Studio IDE.

Prerequisites

You need the following components to complete this walkthrough:

Create the project

Custom task panes are implemented in VSTO Add-ins. Start by creating a VSTO Add-in project for Outlook.

To create a new project

  1. Create an Outlook Add-in project with the name OutlookMailItemTaskPane. Use the Outlook Add-in project template. For more information, see How to: Create Office projects in Visual Studio.

    Visual Studio opens the ThisAddIn.cs or ThisAddIn.vb code file and adds the OutlookMailItemTaskPane project to Solution Explorer.

Design the user interface of the custom task pane

There is no visual designer for custom task panes, but you can design a user control with the UI you want. The custom task pane in this VSTO Add-in has a simple UI that contains a TextBox control. Later in this walkthrough, you will add the user control to the custom task pane.

To design the user interface of the custom task pane

  1. In Solution Explorer, click the OutlookMailItemTaskPane project.

  2. On the Project menu, click Add User Control.

  3. In the Add New Item dialog box, change the name of the user control to TaskPaneControl, and then click Add.

    The user control opens in the designer.

  4. From the Common Controls tab of the Toolbox, drag a TextBox control to the user control.

Design the user interface of the ribbon

One of the goals for this VSTO Add-in is to give users a way to hide or display the custom task pane from the Ribbon of each email message. To provide the user interface, create a custom Ribbon UI that displays a toggle button that users can click to display or hide the custom task pane.

To create a custom Ribbon UI

  1. On the Project menu, click Add New Item.

  2. In the Add New Item dialog box, select Ribbon (Visual Designer).

  3. Change the name of the new Ribbon to ManageTaskPaneRibbon, and click Add.

    The ManageTaskPaneRibbon.cs or ManageTaskPaneRibbon.vb file opens in the Ribbon Designer and displays a default tab and group.

  4. In the Ribbon Designer, click group1.

  5. In the Properties window, set the Label property to Task Pane Manager.

  6. From the Office Ribbon Controls tab of the Toolbox, drag a ToggleButton control onto the Task Pane Manager group.

  7. Click toggleButton1.

  8. In the Properties window, set the Label property to Show Task Pane.

Display the custom Ribbon user interface with email messages

The custom task pane that you create in this walkthrough is designed to appear only with Inspector windows that contain e-mail messages. Therefore, set the properties to display your custom Ribbon UI only with these windows.

To display the custom Ribbon UI with email messages

  1. In the Ribbon Designer, click the ManageTaskPaneRibbon Ribbon.

  2. In the Properties window, click the drop-down list next to RibbonType, and select Microsoft.Outlook.Mail.Compose and Microsoft.Outlook.Mail.Read.

Create a class to manage inspector windows and custom task panes

There are several cases in which the VSTO Add-in must identify which custom task pane is associated with a specific email message. These cases include the following:

  • When the user closes an email message. In this case, the VSTO Add-in must remove the corresponding custom task pane to ensure that resources used by the VSTO Add-in are cleaned up correctly.

  • When the user closes the custom task pane. In this case, the VSTO Add-in must update the state of the toggle button on the ribbon of the email message.

  • When the user clicks the toggle button on the ribbon. In this case, the VSTO Add-in must hide or display the corresponding task pane.

    To enable the VSTO Add-in to keep track of which custom task pane is associated with each open email message, create a custom class that wraps pairs of Inspector and CustomTaskPane objects. This class creates a new custom task pane object for each email message, and it deletes the custom task pane when the corresponding email message is closed.

To create a class to manage inspector windows and custom task panes

  1. In Solution Explorer, right-click the ThisAddIn.cs or ThisAddIn.vb file, and then click View Code.

  2. Add the following statements to the top of the file.

    using Microsoft.Office.Tools;
    
    Imports System.Collections.Generic
    Imports Microsoft.Office.Tools
    Imports Office = Microsoft.Office.Core
    Imports Outlook = Microsoft.Office.Interop.Outlook
    
  3. Add the following code to the ThisAddIn.cs or ThisAddIn.vb file, outside the ThisAddIn class (for Visual C#, add this code inside the OutlookMailItemTaskPane namespace). The InspectorWrapper class manages a pair of Inspector and CustomTaskPane objects. You will complete the definition of this class in the following steps.

    public class InspectorWrapper
    {
        private Outlook.Inspector inspector;
        private CustomTaskPane taskPane;
    
    Public Class InspectorWrapper
        Private inspector As Outlook.Inspector
        Private WithEvents inspectorEvents As Outlook.InspectorEvents_Event
        Private WithEvents taskPane As CustomTaskPane
    
  4. Add the following constructor after the code that you added in the previous step. This constructor creates and initializes a new custom task pane that is associated with the Inspector object that is passed in. In C#, the constructor also attaches event handlers to the Close event of the Inspector object and to the VisibleChanged event of the CustomTaskPane object.

    public InspectorWrapper(Outlook.Inspector Inspector)
    {
        inspector = Inspector;
        ((Outlook.InspectorEvents_Event)inspector).Close +=
            new Outlook.InspectorEvents_CloseEventHandler(InspectorWrapper_Close);
        
        taskPane = Globals.ThisAddIn.CustomTaskPanes.Add(
            new TaskPaneControl(), "My task pane", inspector);
        taskPane.VisibleChanged += new EventHandler(TaskPane_VisibleChanged);
    }
    
    Public Sub New(ByVal Inspector As Outlook.Inspector)
        Me.inspector = Inspector
        inspectorEvents = TryCast(Me.inspector, Outlook.InspectorEvents_Event)
        taskPane = Globals.ThisAddIn.CustomTaskPanes.Add(New TaskPaneControl(), _
            "My task pane", Inspector)
    End Sub
    
  5. Add the following method after the code that you added in the previous step. This method is an event handler for the VisibleChanged event of the CustomTaskPane object that is contained in the InspectorWrapper class. This code updates the state of the toggle button whenever the user opens or closes the custom task pane.

    void TaskPane_VisibleChanged(object sender, EventArgs e)
    {
        Globals.Ribbons[inspector].ManageTaskPaneRibbon.toggleButton1.Checked = 
            taskPane.Visible;
    }
    
    Private Sub TaskPane_VisibleChanged(ByVal sender As Object, ByVal e As EventArgs) _
        Handles taskPane.VisibleChanged
        Globals.Ribbons(inspector).ManageTaskPaneRibbon.ToggleButton1.Checked = taskPane.Visible
    End Sub
    
  6. Add the following method after the code that you added in the previous step. This method is an event handler for the Close event of the Inspector object that contains the current email message. The event handler frees resources when the email message is closed. The event handler also removes the current custom task pane from the CustomTaskPanes collection. This helps prevent multiple instances of the custom task pane when the next email message is opened.

    void InspectorWrapper_Close()
    {
        if (taskPane != null)
        {
            Globals.ThisAddIn.CustomTaskPanes.Remove(taskPane);
        }
    
        taskPane = null;
        Globals.ThisAddIn.InspectorWrappers.Remove(inspector);
        ((Outlook.InspectorEvents_Event)inspector).Close -=
            new Outlook.InspectorEvents_CloseEventHandler(InspectorWrapper_Close);
        inspector = null;
    }
    
    Sub InspectorWrapper_Close() Handles inspectorEvents.Close
        If Not (taskPane Is Nothing) Then
            Globals.ThisAddIn.CustomTaskPanes.Remove(taskPane)
        End If
    
        taskPane = Nothing
        Globals.ThisAddIn.InspectorWrappers.Remove(inspector)
        RemoveHandler inspectorEvents.Close, AddressOf InspectorWrapper_Close
        inspector = Nothing
    End Sub
    
  7. Add the following code after the code that you added in the previous step. Later in this walkthrough, you will call this property from a method in the custom Ribbon UI to display or hide the custom task pane.

        public CustomTaskPane CustomTaskPane
        {
            get
            {
                return taskPane;
            }
        }
    }
    
        Public ReadOnly Property CustomTaskPane() As CustomTaskPane
            Get
                Return taskPane
            End Get
        End Property
    End Class
    

Initialize and clean up resources used by the Add-in

Add code to the ThisAddIn class to initialize the VSTO Add-in when it is loaded, and to clean up resources used by the VSTO Add-in when it is unloaded. You initialize the VSTO Add-in by setting up an event handler for the NewInspector event and by passing all existing email messages to this event handler. When the VSTO Add-in is unloaded, detach the event handler and clean up objects used by the VSTO Add-in.

To initialize and clean up resources used by the VSTO Add-in

  1. In the ThisAddIn.cs or ThisAddIn.vb file, locate the definition of the ThisAddIn class.

  2. Add the following declarations to the ThisAddIn class:

    • The inspectorWrappersValue field contains all the Inspector and InspectorWrapper objects that are managed by the VSTO Add-in.

    • The inspectors field maintains a reference to the collection of Inspector windows in the current Outlook instance. This reference prevents the garbage collector from freeing the memory that contains the event handler for the NewInspector event, which you will declare in the next step.

      private Dictionary<Outlook.Inspector, InspectorWrapper> inspectorWrappersValue =
          new Dictionary<Outlook.Inspector, InspectorWrapper>();
      private Outlook.Inspectors inspectors;
      
      Private inspectorWrappersValue As New Dictionary(Of Outlook.Inspector, InspectorWrapper)
      Private WithEvents inspectors As Outlook.Inspectors
      
  3. Replace the ThisAddIn_Startup method with the following code. This code attaches an event handler to the NewInspector event, and it passes every existing Inspector object to the event handler. If the user loads the VSTO Add-in after Outlook is already running, the VSTO Add-in uses this information to create custom task panes for all email messages that are already open.

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        inspectors = this.Application.Inspectors;
        inspectors.NewInspector +=
            new Outlook.InspectorsEvents_NewInspectorEventHandler(
            Inspectors_NewInspector);
    
        foreach (Outlook.Inspector inspector in inspectors)
        {
            Inspectors_NewInspector(inspector);
        }
    }
    
    Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles Me.Startup
    
        inspectors = Me.Application.Inspectors
        Dim inspector As Outlook.Inspector
        For Each inspector In inspectors
            Inspectors_NewInspector(inspector)
        Next inspector
    End Sub
    
  4. Replace the ThisAddIn_ShutDown method with the following code. This code detaches the NewInspector event handler and cleans up objects used by the VSTO Add-in.

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
        inspectors.NewInspector -=
            new Outlook.InspectorsEvents_NewInspectorEventHandler(
            Inspectors_NewInspector);
        inspectors = null;
        inspectorWrappersValue = null;
    }
    
    Private Sub ThisAddIn_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles Me.Shutdown
    
        RemoveHandler inspectors.NewInspector, AddressOf Inspectors_NewInspector
        inspectors = Nothing
        inspectorWrappersValue = Nothing
    End Sub
    
  5. Add the following NewInspector event handler to the ThisAddIn class. If a new Inspector contains an email message, the method creates an instance of a new InspectorWrapper object to manage the relationship between the e-mail message and the corresponding task pane.

    void Inspectors_NewInspector(Outlook.Inspector Inspector)
    {
        if (Inspector.CurrentItem is Outlook.MailItem)
        {
            inspectorWrappersValue.Add(Inspector, new InspectorWrapper(Inspector));
        }
    }
    
    Sub Inspectors_NewInspector(ByVal Inspector As Outlook.Inspector) _
        Handles inspectors.NewInspector
    
        If TypeOf Inspector.CurrentItem Is Outlook.MailItem Then
            inspectorWrappersValue.Add(Inspector, New InspectorWrapper(Inspector))
        End If
    End Sub
    
  6. Add the following property to the ThisAddIn class. This property exposes the private inspectorWrappersValue field to code outside the ThisAddIn class.

    public Dictionary<Outlook.Inspector, InspectorWrapper> InspectorWrappers
    {
        get
        {
            return inspectorWrappersValue;
        }
    }
    
    Public ReadOnly Property InspectorWrappers() As Dictionary(Of Outlook.Inspector, InspectorWrapper)
        Get
            Return inspectorWrappersValue
        End Get
    End Property
    

Checkpoint

Build your project to ensure that it compiles without errors.

To build your project

  1. In Solution Explorer, right-click the OutlookMailItemTaskPane project and then click Build. Verify that the project compiles without errors.

Synchronize the Ribbon toggle button with the custom task pane

The toggle button will appear to be pressed in when the task pane is visible, and it will appear to be not pressed in when the task pane is hidden. To synchronize the state of the button with the custom task pane, modify the Click event handler of the toggle button.

To synchronize the custom task pane with the toggle button

  1. In the Ribbon Designer, double-click the Show Task Pane toggle button.

    Visual Studio automatically generates an event handler named toggleButton1_Click, which handles the Click event of the toggle button. Visual Studio also opens the ManageTaskPaneRibbon.cs or ManageTaskPaneRibbon.vb file in the Code Editor.

  2. Add the following statements to the top of the ManageTaskPaneRibbon.cs or ManageTaskPaneRibbon.vb file.

    using Outlook = Microsoft.Office.Interop.Outlook;
    using Microsoft.Office.Tools;
    
    Imports Microsoft.Office.Tools.Ribbon
    Imports Outlook = Microsoft.Office.Interop.Outlook
    Imports Microsoft.Office.Tools
    
  3. Replace the toggleButton1_Click event handler with the following code. When the user clicks the toggle button, this method hides or displays the custom task pane that is associated with the current Inspector window.

    private void toggleButton1_Click(object sender, RibbonControlEventArgs e)
    {
        Outlook.Inspector inspector = (Outlook.Inspector)e.Control.Context;
        InspectorWrapper inspectorWrapper = Globals.ThisAddIn.InspectorWrappers[inspector];
        CustomTaskPane taskPane = inspectorWrapper.CustomTaskPane;
        if (taskPane != null)
        {
            taskPane.Visible = ((RibbonToggleButton)sender).Checked;
        }
    }
    
    Private Sub ToggleButton1_Click(ByVal sender As System.Object, _
        ByVal e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) _
        Handles ToggleButton1.Click
    
        Dim inspector As Outlook.Inspector = e.Control.Context
        Dim inspectorWrapper As InspectorWrapper = Globals.ThisAddIn.InspectorWrappers(inspector)
        Dim taskPane As CustomTaskPane = inspectorWrapper.CustomTaskPane
        If Not (taskPane Is Nothing) Then
            taskPane.Visible = TryCast(sender, RibbonToggleButton).Checked
        End If
    End Sub
    

Test the project

When you start debugging the project, Outlook opens and the VSTO Add-in is loaded. The VSTO Add-in displays a unique instance of the custom task pane with each email message that is opened. Create several new email messages to test the code.

To test the VSTO Add-in

  1. Press F5.

  2. In Outlook, click New to create a new email message.

  3. On the ribbon of the email message, click the Add-Ins tab, and then click the Show Task Pane button.

    Verify that a task pane with the title My task pane is displayed with the email message.

  4. In the task pane, type First task pane in the text box.

  5. Close the task pane.

    Verify that the state of the Show Task Pane button changes so that it is no longer pressed.

  6. Click the Show Task Pane button again.

    Verify that the task pane opens, and that the text box still contains the string First task pane.

  7. In Outlook, click New to create a second email message.

  8. On the ribbon of the email message, click the Add-Ins tab, and then click the Show Task Pane button.

    Verify that a task pane with the title My task pane is displayed with the email message, and the text box in this task pane is empty.

  9. In the task pane, type Second task pane in the text box.

  10. Change focus to the first email message.

    Verify that the task pane that is associated with this email message still displays First task pane in the text box.

    This VSTO Add-in also handles more advanced scenarios that you can try. For example, you can test the behavior when viewing emails by using the Next Item and Previous Item buttons. You can also test the behavior when you unload the VSTO Add-in, open several email messages, and then reload the VSTO Add-in.

Next steps

You can learn more about how to create custom task panes from these topics:

See also