Creating PowerPoint 2007 Add-Ins by Using Visual Studio 2005 Tools for the Office System SE

Summary:   Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office system provides templates for building add-ins for Microsoft Office PowerPoint 2007. Learn how to create an add-in that takes advantage of the features you find in PowerPoint 2007. (19 printed pages)

Ken Getz, MCW Technologies, LLC

Jan Fransen, A23 Consulting

November 2007

Applies to:   Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office system, Microsoft Office PowerPoint 2007

Contents

  • Overview

  • Creating PowerPoint Add-Ins

  • Reacting to Application-Level Events

  • Adding Custom Office Fluent Ribbons

  • Building Custom Task Panes

  • Conclusion

  • Additional Resources

Overview

For years, developers and power users developed add-ins for Microsoft Office PowerPoint, either by writing Microsoft Visual Basic for Applications (VBA) code or by creating a COM add-in that targeted PowerPoint. Although both of these techniques still work with Microsoft Office PowerPoint 2007, you can now use Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office system to create add-ins for PowerPoint 2007 in either Microsoft Visual Basic or Microsoft Visual C#.

In this article, you walk through the steps to create an add-in that works with the PowerPoint object model to accomplish some simple tasks. You learn how to write code in Visual Basic or Visual C# that responds to an application-level event. You also find out how to use Visual Studio 2005 Tools for the 2007 Office system to take advantage of two new features in PowerPoint 2007: the Microsoft Office Fluent Ribbon and the custom task pane.

We will not spend time describing the PowerPoint 2007 object model here. For examples of how you can use the PowerPoint 2007 objects in Visual Basic, see Office Add-Ins: Develop Add-Ins for PowerPoint and Visio Using VSTO.

Creating PowerPoint Add-Ins

After you install Visual Studio 2005 Tools for the 2007 Office system, you find several new templates for creating add-ins that target different products. To create an add-in for PowerPoint 2007, follow these steps.

To create an add-in for PowerPoint 2007

  1. Start Visual Studio 2005.

  2. On the File menu, click New Project to open the New Project dialog box.

  3. Expand either the Visual Basic node or the Visual C# node. Depending on how you configured Visual Studio, you may find your language of choice under the Other Languages node.

  4. Expand the Office node and select Office 2007 Add-ins, as shown in Figure 1.

    Figure 1. Visual Studio 2005 project types

    Visual Studio 2005 project types

  5. In the Templates pane, select PowerPoint Add-in.

  6. Provide a name, for example, PPTSetPrintProperties, and a location for your add-in.

  7. Click OK.

Visual Studio uses the template you selected to create a solution that includes two projects: the add-in project and a setup project that you can use to help deploy the completed add-in.

Take a moment to examine the add-in project. It contains a class module named ThisAddIn with two event handlers: ThisAddIn_Startup and ThisAddIn_Shutdown. The ThisAddIn_Startup method handles the Startup event for the add-in, which is raised after the application is running and all its initialization code has run. The ThisAddIn_Shutdown method handles the Shutdown event for the add-in, which is raised when the application hosting the add-in is about to unload, or when the user chooses to unload the add-in through the user interface.

If you are using Visual C#, you can use the ThisAddIn class to define a set of namespaces that you are likely to use as you write the code for your add-in.

using System;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools;

The Visual Basic template imports these namespaces also, but it does so at a project level so you do not see a similar list in the ThisAddIn.vb class module.

The ThisAddIn class includes two members that you use to communicate with PowerPoint:

  • The Application object refers to the current instance of PowerPoint.

  • The CustomTaskPanes collection enables you to add and work with custom task panes in your add-in.

Reacting to Application-Level Events

The PowerPoint object model provides a number of application-level events, so that you can react to these events and handle them in your managed code. If you wrote VBA code to handle a PowerPoint application event and you are now writing code in Visual Basic, the process looks familiar. If you are writing code in Visual C#, you need to take a few extra steps.

To illustrate the process, suppose you want to write code that adds a copyright statement to the bottom of every slide in each new presentation you create. The Application class provides the event you need. The NewPresentation event runs when the user creates a presentation, or when PowerPoint creates a presentation at startup.

Writing the Object Model Code

To write the code that inserts the copyright statement, follow these steps.

  1. Open the ThisAddIn class, if it is not already open.

  2. Add a procedure to insert a copyright statement at the bottom of the slide master for a given presentation.

    Private Sub InsertCopyright( _
     ByVal presentation As PowerPoint.Presentation)
        Dim master As PowerPoint.Master = _
         presentation.SlideMaster
    
        Dim shape As PowerPoint.Shape = _
         presentation.SlideMaster.Shapes.AddTextbox( _
         Microsoft.Office.Core.MsoTextOrientation. _
         msoTextOrientationHorizontal, _
         0, master.Height - 50, master.Width, 50)
        Dim textRange As PowerPoint.TextRange = _
         shape.TextFrame.TextRange
        textRange.Text = "Copyright 2007, Microsoft Corporation"
        textRange.Paragraphs.ParagraphFormat.Alignment = _
         PowerPoint.PpParagraphAlignment.ppAlignCenter
    End Sub
    
    private void InsertCopyright(PowerPoint.Presentation presentation)
    { 
        PowerPoint.Master master = presentation.SlideMaster;
        PowerPoint.Shape shape =
         presentation.SlideMaster.Shapes.AddTextbox(
         Microsoft.Office.Core.
         MsoTextOrientation.msoTextOrientationHorizontal,
         0, master.Height - 50, master.Width, 50);
        PowerPoint.TextRange textRange = shape.TextFrame.TextRange;
        textRange.Text = "Copyright 2007, Microsoft Corporation";
        textRange.Paragraphs(1,1).ParagraphFormat.Alignment =
         PowerPoint.PpParagraphAlignment.ppAlignCenter;
    }
    

Hooking Up the Event Handler

If you are working with Visual Basic, follow these steps to hook up the event handler.

To hook up the event handler in Visual Basic

  1. In the Class Name drop-down list at the top of the ThisAddIn code window, select Application.

  2. In the Method Name drop-down list, select NewPresentation.

    You might look at the different events of the Application class that you can handle from a PowerPoint add-in. Notice that the Application_NewPresentation method includes a parameter named Pres, which is a reference to the presentation you just created.

  3. Add code to call the InsertCopyright procedure when the NewPresentation event is triggered.

    Private Sub Application_NewPresentation( _
     ByVal Pres As _
     PowerPoint.Presentation) _
     Handles Application.NewPresentation
        InsertCopyright(Pres)
    End Sub
    

The PowerPoint object model includes more than one interface to handle events. The wrappers around the object model that you use with Visual Basic determine where the event handler resides and handles the communication for you. However, in Visual C#, you need to cast the Application object to the specific interface that contains the event you want to handle, and you must explicitly add the handler.

To add the event handler in Visual C#, follow these steps.

To add the event handler in Visual C#

  1. In the ThisAddIn_Startup method, type the following code.

    ((PowerPoint.EApplication_Event)this.Application).NewPresentation += 
    
  2. After you type the = character, press TAB to add a new event handler for the NewPresentation event.

  3. After inserting the event handler code, press TAB to generate the event handler procedure. The code now looks like this.

    ((PowerPoint.EApplication_Event)this.Application).NewPresentation +=
    new Microsoft.Office.Interop.PowerPoint.
    EApplication_NewPresentationEventHandler(
    ThisAddIn_NewPresentation);
    
  4. Scroll down to the new ThisAddIn_NewPresentation method and change its code to call the InsertCopyright method.

    void ThisAddIn_NewPresentation(
     Microsoft.Office.Interop.PowerPoint.Presentation Pres)
     {
         InsertCopyright(Pres);
     }
    

Testing the Event Handler

Now that you wrote the code to handle the event, follow these steps to test the add-in.

To test the add-in

  1. Press CTRL+F5 to compile the solution and run PowerPoint.

  2. After PowerPoint is loaded, PowerPoint loads your add-in. Notice the copyright statement at the bottom of the title slide in the new presentation.

  3. Click the Microsoft Office Button, and then click New.

  4. In the New Presentation dialog box, select Blank Presentation and click Create. PowerPoint creates a new presentation with your custom copyright statement.

  5. Close PowerPoint without saving the presentations.

Adding Custom Office Fluent Ribbons

In PowerPoint 2007, the Office Fluent Ribbon replaces the menu and command bars of previous versions of Microsoft Office PowerPoint. You can add your own tabs, groups, and controls; and you can hide built-in controls or override the behavior for built-in controls. For more details on the Office Fluent Ribbon in general, and on the specifics of working with each control type, see the Office Fluent User Interface Developer Portal.

TipTip

If you wrote VBA solutions that use custom command bar buttons, those solutions work in PowerPoint 2007. When you load your add-in in PowerPoint 2007, you find all custom command bars in the Add-Ins tab.

In general, you can customize the Office Fluent Ribbon in two different ways.

  • Add Office Fluent Ribbon markup directly to Open XML Format files (Microsoft Office Word 2007, Microsoft Office Excel 2007, and Microsoft Office PowerPoint 2007) by inserting the XML part into the document. In this case, you handle Office Fluent Ribbon interaction and events by using VBA code in the document itself.

  • Create an add-in that provides the Office Fluent Ribbon markup and event-handling code. The add-in might be a Visual Studio 2005 shared add-in, or a Visual Studio 2005 Tools for the 2007 Office system add-in like the one discussed in this article.

Office Fluent Ribbon customization involves two parts: You must provide the XML markup that defines the content of the customization, and you must provide code (either VBA or managed code) that reacts to Office Fluent Ribbon control events and provides dynamic content for the Office Fluent Ribbon.

This section walks through a simple Office Fluent Ribbon customization that adds a button to a custom tab. When the user clicks the button, the add-in runs code to print the active presentation in a specific format. To customize the Office Fluent Ribbon, follow these steps.

To customize the Office Fluent Ribbon

  1. In Visual Studio 2005, click Project, and then click Add New Item.

  2. In the Add New Item dialog box, click Ribbon Support. Accept the default name (Ribbon1.vb or Ribbon1.cs), and click Add. This action adds two new items to your project: Ribbon1.vb (or Ribbon1.cs) and Ribbon1.xml.

  3. Open Ribbon1.xml, and you can see that it contains declarative information about the items that should appear on the Add-Ins tab on the Office Fluent Ribbon.

    <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="OnLoad">
      <ribbon>
        <tabs>
          <tab idMso="TabAddIns">
            <group id="MyGroup"
                   label="My Group">
              <toggleButton id="toggleButton1" 
                            size="large"
                            label="My Button"
                            screentip="My Button Screentip"
                            onAction="OnToggleButton1" 
                            imageMso="HappyFace" />
            </group>
          </tab>
        </tabs>
      </ribbon>
    </customUI>
    

    This XML indicates that you are adding a new group named MyGroup to the Add-Ins tab. Within the group, you are creating a toggle button that displays the text My Button and a happy face image. Click the button to run a procedure named OnToggleButton1 in the add-in.

    For this example, the code runs your code from a button rather than a toggle button. The button is on a new tab named Common Tasks.

  4. Replace the contents of Ribbon1.xml with the following markup.

    <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="OnLoad">
      <ribbon>
        <tabs>
          <tab id="CommonTasksAddIns" label="Common Tasks">
            <group id="Group1"
                   label="My Stuff" visible="true">
              <button id="SetPrint"
                      label="Print 2"
                      size="large"
                      screentip ="Print two framed slides per page"
                      onAction="PrintButtonClick"
                      imageMso="FilePrintQuick" />
            </group>
          </tab>
        </tabs>
      </ribbon>
    </customUI>
    

    In a later step, you write code for the PrintButtonClick procedure specified in the onAction attribute for the button.

    To be sure your XML markup is always available to the project, store it in the project resources.

  5. On the Project menu, click PPTSetPrintProperties properties.

  6. Click the Resources tab to display the project resources.

  7. In Solution Explorer, drag Ribbon1.xml into the Resources window. This action creates a file resource that you can refer to from within your code.

  8. Close the Properties window, saving when prompted.

    The Ribbon1 module contains the code to hook up the custom Ribbon.

  9. In Solution Explorer, double-click the Ribbon1.vb or Ribbon1.cs file to examine its code.

  10. In a later step, you add code to this class that interacts with the PowerPoint object model. If you are using Visual C#, add a using statement at the top of the file so you can access the PowerPoint namespace.

    using PowerPoint=Microsoft.Office.Interop.PowerPoint;
    namespace PPTSetPrintProperties
    

    The Ribbon1 file contains a commented-out partial class named ThisAddIn. This code connects the Ribbon named Ribbon1 to the add-in, and tells Visual Studio 2005 Tools for the 2007 Office system where it can find this particular Ribbon customization. You must uncomment the code in order for the add-in to work.

  11. Select the entire partial class named ThisAddIn (but not the comments immediately above it), and click the Uncomment the selected lines button, as shown in Figure 2.

    Figure 2. The Uncomment the selected lines button

    The Uncomment the selected lines button

  12. Scroll down in the Ribbon1 file to find the Ribbon1 class, which describes the behavior of your Office Fluent Ribbon customization.

  13. Modify the GetCustomUI method so that it uses the Ribbon1.xml file stored as a resource.

    Public Function GetCustomUI( _
      ByVal ribbonID As String) As String _
      Implements Office.IRibbonExtensibility.GetCustomUI
        Return My.Resources.Ribbon1
    End Function
    
    Public string GetCustomUI(string ribbonID)
    {
        return Properties.Resources.Ribbon1;
    }
    
  14. Expand the Ribbon Callbacks code region to find the OnToggleButton1 procedure. The isPressed parameter displays different text when the user presses and releases the toggle button. You do not need this sample code for your Office Fluent Ribbon customization, so you can delete it.

  15. Add a PrintButtonClick procedure that prints the presentation two slides per page in black and white to the Ribbon Callbacks section.

    Public Sub PrintButtonClick( _
     ByVal control As Office.IRibbonControl)
        Dim presentation As PowerPoint.Presentation = _
         Globals.ThisAddIn.Application.ActivePresentation
        Dim options As PowerPoint.PrintOptions = _
         presentation.PrintOptions
        options.OutputType = _
         PowerPoint.PpPrintOutputType.ppPrintOutputTwoSlideHandouts
        options.FrameSlides = _
         Microsoft.Office.Core.MsoTriState.msoCTrue
        options.PrintColorType = _
         PowerPoint.PpPrintColorType.ppPrintPureBlackAndWhite
        options.PrintInBackground = _
         Microsoft.Office.Core.MsoTriState.msoCTrue
        presentation.PrintOut()
    End Sub
    
    public void PrintButtonClick(Office.IRibbonControl control)
    {
        PowerPoint.Presentation presentation = 
         Globals.ThisAddIn.Application.ActivePresentation;
        PowerPoint.PrintOptions options = 
         presentation.PrintOptions;
        options.OutputType = 
         PowerPoint.PpPrintOutputType.ppPrintOutputTwoSlideHandouts;
        options.FrameSlides = 
         Microsoft.Office.Core.MsoTriState.msoCTrue;
        options.PrintColorType = 
         PowerPoint.PpPrintColorType.ppPrintPureBlackAndWhite;
        options.PrintInBackground = 
         Microsoft.Office.Core.MsoTriState.msoTrue;
        presentation.PrintOut( 
         1,presentation.Slides.Count,String.Empty,
         1,Microsoft.Office.Core.MsoTriState.msoFalse);
    }
    
    NoteNote

    If you compare the call to the PrintOut method in Visual Basic to the call in Visual C#, you can see that the Visual C# version includes a list of arguments. The PrintOut method provides five optional parameters, but Visual C# does not support optional parameters. Therefore, although you can simply accept the default values if you are writing Visual Basic code, you must provide a value for each parameter if you are writing Visual C# code.

  16. Save and run your add-in. In PowerPoint, click the new Common Tasks tab, and notice the new Print button on the Office Fluent Ribbon, as shown in Figure 3.

    Figure 3. The new Print button on the Common Tasks tab on the Office Fluent Ribbon

    The new Print button on the Common Tasks tab

  17. Create a few slides in the active presentation and click the Print 2 button. The presentation prints to the default printer, two slides per page, using pure black and white.

  18. Close PowerPoint when you finish, and return to Visual Studio.

Building Custom Task Panes

In Visual Studio 2005 Tools for the 2007 Office system, you can add custom task panes to your PowerPoint add-ins. To create a custom task pane, you start by creating a user control—a control that enables you to combine multiple other controls. When you want to display the task pane, you add an instance of your custom control to a new member of the CustomTaskPanes collection for the add-in. The user control code can interact with PowerPoint in whatever way you like.

Creating User Controls for the Custom Task Pane

The custom task pane described in this section uses navigation buttons to move from one slide to the next. To create a user control for the custom task pane, follow these steps.

To create a user control for the custom task pane

  1. Return to your project in Visual Studio 2005.

  2. Click Project, and then click Add User Control. In the Add New Item dialog box, type a name for your user control, SampleTaskPane and click Add. Visual Studio displays a designer for your control.

  3. Use the Properties window to change the control size to 179, 200.

  4. Use the Toolbox to add four buttons to the user control. Set their properties as shown in the following table.

    Table 1. Button properties

    Button Name

    Property

    Value

    Button1

    Name

    firstButton

    Location

    3,6

    Size

    37,21

    Text

    |<

    Button2

    Name

    previousButton

    Location

    40,6

    Size

    37,21

    Text

    <

    Button3

    Name

    nextButton

    Location

    86,6

    Size

    37,21

    Text

    >

    Button4

    Name

    lastButton

    Location

    129,6

    Size

    37,21

    Text

    >|

  5. Right-click anywhere on the task pane, and then click View Code.

  6. If you are using Visual C#, add a using statement at the top of the file so you can access the PowerPoint namespace.

    using PowerPoint=Microsoft.Office.Interop.PowerPoint;
    
  7. In the SampleTaskPane class, add an enumeration for the four button actions.

    Private Enum ButtonActions
        MoveFirst
        MovePrevious
        MoveNext
        MoveLast
    End Enum
    
    enum buttonActions {
        MoveFirst,
        MovePrevious,
        MoveNext,
        MoveLast
    }
    
  8. Add a method to handle moving through the slides. The method includes a ButtonActions parameter so that the calling code can specify which slide to move to. Start the code by adding a try/catch block. The eventual navigation code does not check to see if the move is possible, so you need to catch any exceptions. For this example, you do not need to take any action if an exception is thrown.

    Private Sub HandleButtons(ByVal action As ButtonActions)
        Try
    
        Catch ex As Exception
            ' If an error occurs, just do nothing at all.
            ' Because the code is not checking to ensure
            ' that it can actually navigate correctly, 
            ' it is likely that errors will occur.
        End Try
    End Sub
    
    private void HandleButtons(buttonActions action)
    {
        try
        {
        }
        catch
        { 
           // If any error occurs, just do nothing at all.
           // Because the code is not checking to ensure
           // that it can actually navigate correctly, 
           // it is likely that errors will occur.
        }
    }
    
  9. Within the try block, define some variables to help you navigate from the active slide to the specified slide. The ThisAddIn class includes a reference to the PowerPoint Application object, and the Globals class makes this information available to you in any class within the add-in. Use the Globals.ThisAddin.Application object to refer to any other objects in the current PowerPoint instance.

    Dim app As PowerPoint.Application = _
     Globals.ThisAddIn.Application
    
    PowerPoint.Application app = 
     Globals.ThisAddIn.Application;
    
  10. After you have a reference to the Application object, you can find out how many slides are in the active presentation in case you want to move to the last slide. You can also need to find out the number of the active slide. Finally, you can define a variable to refer to the presentation’s active view. Use the GoToSlide method of this object to navigate from one slide to another. Continue adding code to the try block.

    Dim slideCount As Integer = _
     app.ActivePresentation.Slides.Count
    Dim slide As PowerPoint.Slide = _
     CType(app.ActiveWindow.View.Slide, _
     PowerPoint.Slide)
    
    Dim slideIndex As Integer = slide.SlideIndex
    Dim view As PowerPoint.View = app.ActiveWindow.View
    
    int slideCount = app.ActivePresentation.Slides.Count;
    PowerPoint.Slide slide = (PowerPoint.Slide)app.ActiveWindow.View.Slide;
    int slideIndex = slide.SlideIndex;
    PowerPoint.View view = app.ActiveWindow.View;
    
  11. Finally, add a statement that checks the value of the action argument and moves accordingly, continuing to add code to the try block.

    Select Case action
        Case ButtonActions.MoveFirst
            view.GotoSlide(1)
        Case ButtonActions.MoveLast
            view.GotoSlide(slideCount)
        Case ButtonActions.MoveNext
            view.GotoSlide(slideIndex + 1)
        Case ButtonActions.MovePrevious
             view.GotoSlide(slideIndex - 1)
    End Select
    
    switch (action)
    {
        case buttonActions.MoveFirst:
            view.GotoSlide(1);
            break;
        case buttonActions.MoveLast:
            view.GotoSlide(slideCount);
            break;
        case buttonActions.MoveNext:
            view.GotoSlide(slideIndex + 1);
            break;
        case buttonActions.MovePrevious:
            view.GotoSlide(slideIndex - 1);
            break;
    }
    
  12. Add the code for the Click event handlers of the buttons themselves. In Visual Basic, you can use the Class Name drop-down list to select firstButton, and the Method Name drop-down list to select Click. In Visual C#, move to the design view for the user control and double-click firstButton to create an event handler procedure.

  13. Add code to the firstButton_Click event handler to call HandleButtons.

    Private Sub firstButton_Click( _
     ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles firstButton.Click
        HandleButtons(ButtonActions.MoveFirst)
    End Sub
    
    private void firstButton_Click(object sender, EventArgs e)
    {
        HandleButtons(buttonActions.MoveFirst);
    }
    
  14. Follow the same steps to add code for the other three navigation buttons.

    Private Sub previousButton_Click( _
     ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles previousButton.Click
         HandleButtons(ButtonActions.MovePrevious)
    End Sub
    
    Private Sub lastButton_Click( _
     ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles lastButton.Click
        HandleButtons(ButtonActions.MoveLast)
    End Sub
    
    Private Sub nextButton_Click( _
     ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles nextButton.Click
        HandleButtons(ButtonActions.MoveNext)
    End Sub
    
    private void previousButton_Click(object sender, EventArgs e)
    {
        HandleButtons(buttonActions.MovePrevious);
    }
    private void nextButton_Click(object sender, EventArgs e)
    {
        HandleButtons(buttonActions.MoveNext);
    }
    private void lastButton_Click(object sender, EventArgs e)
    {
        HandleButtons(buttonActions.MoveLast);
    }
    

    The user control is now ready to be a part of a custom task pane.

Opening the Task Pane from the Ribbon

Your next task is to change the code for the Office Fluent Ribbon to add a toggle button that opens and closes the task pane. Follow these steps.

To add a toggle button to the Ribbon

  1. Open the Ribbon1.xml file.

  2. Within the group node, add the markup for a toggle button to open and close the custom task pane. If you still have the original toggleButton1 markup in the XML file, replace it with this XML content.

    <toggleButton id="navigationTaskPaneToggleButton"
        size="large"
        label="Navigation Pane"
        screentip="Show or hide the navigation task pane"
        imageMso="Diamond"
        onAction="HandleTaskPane"/>
    
  3. Before you can use a custom task pane, you need to add it to the CustomTaskPanes collection for the add-in. To add the custom task pane and declare a variable to point to it, open the ThisAddIn.vb or ThisAddIn.cs file.

  4. The CustomTaskPane class is in the Microsoft.Office.Tools namespace, so add a statement to the top of the file to import the namespace.

    Imports Microsoft.Office.Tools
    
    using Microsoft.Office.Tools;
    
  5. Within the class, add a public variable that refers to custom task pane.

    Public ctp As CustomTaskPane = Nothing
    
    public CustomTaskPane ctp = null;
    
  6. Modify the ThisAddIn_Startup procedure by adding an instance of the user control to the CustomTaskPanes collection.

    Private Sub ThisAddIn_Startup( _
     ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles Me.Startup
        ctp = Me.CustomTaskPanes.Add( _
         New SampleTaskPane, "Slide Navigation")
        ctp.Width =- 250
        ctp.Visible = True
    End Sub
    
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
      ((PowerPoint.EApplication_Event)this.Application).
        NewPresentation += new Microsoft.Office.Interop.PowerPoint.
        EApplication_NewPresentationEventHandler(
        ThisAddIn_NewPresentation);
        ctp = this.CustomTaskPanes.Add( 
          new SampleTaskPane(), "Slide Navigation");
        ctp.Width = 250;
        ctp.Visible = true;
    }
    
  7. Open the Ribbon1.vb file and add the HandleTaskPane procedure to the Ribbon1 class to toggle the visibility of the task pane.

    Public Sub HandleTaskPane( _
     ByVal control As Office.IRibbonControl, _
     ByVal isPressed As Boolean)
        Globals.ThisAddIn.ctp.visible = isPressed
    End Sub
    
    public void HandleTaskPane(Office.IRibbonControl control, bool isPressed)
    {
        Globals.ThisAddIn.ctp.Visible = isPressed;
    }
    
  8. Save and run your add-in. In PowerPoint, click the new Common Tasks tab to see the toggle button on the Office Fluent Ribbon.

  9. Click the Navigation Pane toggle button. You see the navigation task pane, as shown in Figure 4.

    Figure 4. The Navigation Task Pane in PowerPoint

    The Navigation Task Pane in PowerPoint

  10. Add several slides to the active presentation, or open any presentation.

  11. Use the navigation buttons to move between the slides.

  12. Click the Navigation Pane toggle button to hide the custom task pane.

  13. Leave PowerPoint open for the next section.

Synchronizing the Toggle Button and the Task Pane

Although you can use the toggle button to show and hide the task pane, you can also hide the task pane by clicking its Close button. However, as the solution is currently written, the toggle button does not update to show the actual status of the task pane. You can test the current behavior by following these steps.

To test the current behavior

  1. In PowerPoint, click the Navigation Pane toggle button to show the task pane.

  2. Click the Close button on the task pane to close it.

    Notice that the toggle button remains selected, even though the task pane is now hidden.

  3. Close PowerPoint and return to Visual Studio.

To support dynamic functionality, the Office Fluent Ribbon customization model allows the Ribbon markup to specify callback procedures that handle control state, and handle control events (as you saw in the previous example). For a ToggleButton control, you can specify the getPressed attribute. The value of this attribute supplies the name of a procedure that the Office Fluent Ribbon calls to determine the pressed state of the button. In this procedure, you supply code that calculates whether the button should appear pressed, and returns True to indicate that it is pressed and False to indicate that it is not.

To determine the pressed state of the ToggleButton control

  1. In the Ribbon1 class, add a public procedure that allows code in the add-in class to force the Office Fluent Ribbon to refresh. This code calls the InvalidateControl method for the Office Fluent Ribbon, which forces the specified control to refresh its display.

    Public Sub Refresh()
        ribbon.InvalidateControl("navigationTaskPaneToggleButton")
    End Sub
    
    public void Refresh()
    {
        ribbon.InvalidateControl("navigationTaskPaneToggleButton");
    }
    
  2. In the Ribbon1 class, add the status callback that determines the state of the toggle button, based on the visibility of the custom task pane.

    Public Function GetPressed( _
      ByVal control As Office.IRibbonControl) As Boolean
        Return Globals.ThisAddIn.ctp.Visible
    End Function
    
    public Boolean GetPressed(Office.IRibbonControl control)
    {
        return Globals.ThisAddIn.ctp.Visible;
    }
    
  3. In Ribbon1.xml, add support for retrieving the pressed state of the button by calling the GetPressed method you just created. Modify the XML markup for the toggle button by adding the getPressed attribute, so that it looks like this.

    <toggleButton id="navigationTaskPaneToggleButton"
        size="large"
        label="Navigation Pane"
        screentip="Show or hide the navigation task pane"
        imageMso="Diamond"
        onAction="HandleTaskPane"
        getPressed="GetPressed"/>
    
  4. In the ThisAddIn class in the Ribbon1.vb file, add support for handling the VisibleChanged event for the task pane. Add this event handler to the class, which calls the Refresh method for the Ribbon1 class and updates the pressed state of the toggle button when the visibility changes.

    Private Sub HandleVisibleChanged( _
      ByVal sender As Object, ByVal e As EventArgs)
        ribbon.Refresh()
    End Sub
    
    private void HandleVisibleChanged(Object sender, EventArgs e)
    {
        ribbon.Refresh();
    }
    
  5. Finally, modify the existing Startup and Shutdown procedures in the ThisAddIn.vb file, hooking and unhooking the VisibleChanged event on the task pane.

    Private Sub ThisAddIn_Startup( _
     ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles Me.Startup
        ctp = Me.CustomTaskPanes.Add( _
         New SampleTaskPane, "Slide Navigation")
        ctp.Width = 250
        ctp.Visible = True
        AddHandler ctp.VisibleChanged, AddressOf HandleVisibleChanged
    End Sub
    
    Private Sub ThisAddIn_Shutdown( _
     ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles Me.Shutdown
        RemoveHandler ctp.VisibleChanged, _
         AddressOf HandleVisibleChanged
    End Sub
    
    private void ThisAddIn_Startup(
      object sender, System.EventArgs e)
    {
      ((PowerPoint.EApplication_Event)this.Application).
        NewPresentation += new Microsoft.Office.Interop.PowerPoint.
        EApplication_NewPresentationEventHandler(
        ThisAddIn_NewPresentation);
        ctp = this.CustomTaskPanes.Add(
          new SampleTaskPane(), "Slide Navigation");
        ctp.Width = 250
        ctp.Visible = True
        ctp.VisibleChanged += new EventHandler(HandleVisibleChanged);
    }
    
    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
        ctp.VisibleChanged -= new EventHandler(HandleVisibleChanged);
    }
    
  6. Save and run your project. You can use the toggle button to show and hide the task pane. If you close the task pane manually, the button updates appropriately.

  7. Exit PowerPoint when you finish.

As you can see, customizing the Office Fluent Ribbon takes some effort—Visual Studio does not provide a user interface for performing the customization—but the concepts are not difficult. For more information, be sure to visit the Office Fluent User Interface Developer Portal.

Conclusion

In this article, you learned how to use Visual Studio 2005 Tools for the 2007 Office system to create add-ins for PowerPoint 2007 and discovered the basics of using the PowerPoint 2007 environment. As you have seen, creating an add-in is not complex.

Writing the code for the add-in presents different challenges to developers from different backgrounds.

If you created solutions for PowerPoint in VBA, you need to learn more about the Microsoft .NET Framework and Visual Studio 2005 to adapt to the changes in the 2007 Office system. If your solutions require a user interface, you want to learn more about Windows Forms compared to VBA user forms.

If you already know how to create applications in Visual Basic or Visual C#, but you are new to PowerPoint development, you need to learn more about the PowerPoint object model. Remember that the code used by VBA developers to work with PowerPoint translates almost directly to Visual Studio 2005 Tools for the 2007 Office system, particularly if you use Visual Basic.

About the Authors

Ken Getz is a developer, writer, and trainer, working as a senior consultant with MCW Technologies, LLC., a Microsoft Solution Provider. Ken co-authored AppDev's C#, ASP.NET, VB.NET, and ADO.NET courseware. He has co-authored several technical books for developers, including the best-selling ASP.NET Developer's Jumpstart, the Access Developer's Handbook series, and the VBA Developer's Handbook series. Ken is a technical editor for Advisor Publications' VB.NET Technical Journal, and he is a columnist for both MSDN Magazine and CoDe Magazine. Ken speaks regularly at a large number of industry events, including Advisor Media's Advisor Live events, FTP's VSLive, and Microsoft Tech-Ed.

Jan Fransen is a writer, trainer, and developer specializing in Microsoft products. She authored AppDev’s courses in Microsoft Visual Studio Tools for Office, Microsoft Office, and Visual Basic for Applications, and co-authored AppDev’s .NET Framework 2.0 courseware. She has contributed to books about Microsoft Office, written white papers and technical articles for publication on MSDN, and created samples designed to help developers get up to speed quickly on new Microsoft products and features.

Additional Resources