http://msdn.microsoft.com/en-us/library/bb960904(v=office.12).aspx#Y1700
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, seeOffice 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
Start Visual Studio 2005.
On theFilemenu, clickNew Projectto open theNew Projectdialog box.
Expand either theVisual Basicnode or theVisual C#node. Depending on how you configured Visual Studio, you may find your language of choice under theOther Languagesnode.
Expand theOfficenode and selectOffice 2007 Add-ins, as shown in Figure 1.
Figure 1. Visual Studio 2005 project typesIn theTemplatespane, selectPowerPoint Add-in.
Provide a name, for example,PPTSetPrintProperties, and a location for your add-in.
ClickOK.
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 namedThisAddInwith two event handlers:ThisAddIn_StartupandThisAddIn_Shutdown. TheThisAddIn_Startupmethod handles theStartupevent for the add-in, which is raised after the application is running and all its initialization code has run. TheThisAddIn_Shutdownmethod handles theShutdownevent 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 theThisAddInclass 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.
TheThisAddInclass includes two members that you use to communicate with PowerPoint:
- TheApplicationobject refers to the current instance of PowerPoint.
- TheCustomTaskPanescollection 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. TheApplicationclass provides the event you need. TheNewPresentationevent 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.
To write the code that inserts the copyright statement
Open theThisAddInclass, if it is not already open.
Add a procedure to insert a copyright statement at the bottom of the slide master for a given presentation.
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
In theClass Namedrop-down list at the top of the ThisAddIn code window, selectApplication.
In theMethod Namedrop-down list, selectNewPresentation.
You might look at the different events of theApplicationclass that you can handle from a PowerPoint add-in. Notice that theApplication_NewPresentationmethod includes a parameter namedPres, which is a reference to the presentation you just created.
Add code to call theInsertCopyrightprocedure when theNewPresentationevent is triggered.
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 theApplicationobject 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#
In theThisAddIn_Startupmethod, type the following code.
After you type the = character, press TAB to add a new event handler for theNewPresentationevent.
After inserting the event handler code, press TAB to generate the event handler procedure. The code now looks like this.
Scroll down to the newThisAddIn_NewPresentationmethod and change its code to call theInsertCopyrightmethod.
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
Press CTRL+F5 to compile the solution and run PowerPoint.
After PowerPoint is loaded, PowerPoint loads your add-in. Notice the copyright statement at the bottom of the title slide in the new presentation.
Click theMicrosoft Office Button, and then clickNew.
In theNew Presentationdialog box, selectBlank Presentationand clickCreate. PowerPoint creates a new presentation with your custom copyright statement.
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 theOffice Fluent User Interface Developer Portal.
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 theAdd-Instab. |
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
In Visual Studio 2005, clickProject, and then clickAdd New Item.
In theAdd New Itemdialog box, clickRibbon Support. Accept the default name (Ribbon1.vb or Ribbon1.cs), and clickAdd. This action adds two new items to your project: Ribbon1.vb (or Ribbon1.cs) and Ribbon1.xml.
Open Ribbon1.xml, and you can see that it contains declarative information about the items that should appear on theAdd-Instab 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 namedMyGroupto theAdd-Instab. Within the group, you are creating a toggle button that displays the textMy Buttonand a happy face image. Click the button to run a procedure namedOnToggleButton1in 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 namedCommon Tasks.
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 thePrintButtonClickprocedure specified in theonActionattribute for the button.
To be sure your XML markup is always available to the project, store it in the project resources.
On theProjectmenu, clickPPTSetPrintPropertiesproperties.
Click theResourcestab to display the project resources.
InSolution Explorer, drag Ribbon1.xml into theResourceswindow. This action creates a file resource that you can refer to from within your code.
Close thePropertieswindow, saving when prompted.
The Ribbon1 module contains the code to hook up the custom Ribbon.
InSolution Explorer, double-click the Ribbon1.vb or Ribbon1.cs file to examine its code.
In a later step, you add code to this class that interacts with the PowerPoint object model. If you are using Visual C#, add ausingstatement at the top of the file so you can access the PowerPoint namespace.
TheRibbon1file contains a commented-out partial class namedThisAddIn. This code connects the Ribbon namedRibbon1to 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.
Select the entire partial class namedThisAddIn(but not the comments immediately above it), and click theUncomment the selected linesbutton, as shown in Figure 2.
Figure 2. The Uncomment the selected lines buttonScroll down in theRibbon1file to find theRibbon1class, which describes the behavior of your Office Fluent Ribbon customization.
Modify theGetCustomUImethod so that it uses the Ribbon1.xml file stored as a resource.
Expand theRibbon Callbackscode region to find theOnToggleButton1procedure. TheisPressedparameter 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.
Add aPrintButtonClickprocedure that prints the presentation two slides per page in black and white to theRibbon Callbackssection.
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);}
If you compare the call to thePrintOutmethod in Visual Basic to the call in Visual C#, you can see that the Visual C# version includes a list of arguments. ThePrintOutmethod 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. Save and run your add-in. In PowerPoint, click the newCommon Taskstab, and notice the newPrintbutton 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 RibbonCreate a few slides in the active presentation and click thePrint 2button. The presentation prints to the default printer, two slides per page, using pure black and white.
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 auser 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 theCustomTaskPanescollection 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
Return to your project in Visual Studio 2005.
ClickProject, and then clickAdd User Control. In theAdd New Itemdialog box, type a name for your user control,SampleTaskPaneand clickAdd. Visual Studio displays a designer for your control.
Use thePropertieswindow to change the control size to 179, 200.
Use theToolboxto 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
>|
Right-click anywhere on the task pane, and then clickView Code.
If you are using Visual C#, add ausingstatement at the top of the file so you can access the PowerPoint namespace.
In theSampleTaskPaneclass, add an enumeration for the four button actions.
Add a method to handle moving through the slides. The method includes aButtonActionsparameter so that the calling code can specify which slide to move to. Start the code by adding atry/catchblock. 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.
Within thetryblock, define some variables to help you navigate from the active slide to the specified slide. TheThisAddInclass includes a reference to thePowerPoint Applicationobject, and theGlobalsclass makes this information available to you in any class within the add-in. Use theGlobals.ThisAddin.Applicationobject to refer to any other objects in the current PowerPoint instance.
After you have a reference to theApplicationobject, 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 theGoToSlidemethod of this object to navigate from one slide to another. Continue adding code to thetryblock.
Finally, add a statement that checks the value of theactionargument and moves accordingly, continuing to add code to thetryblock.
Add the code for theClickevent handlers of the buttons themselves. In Visual Basic, you can use theClass Namedrop-down list to selectfirstButton, and theMethod Namedrop-down list to selectClick. In Visual C#, move to the design view for the user control and double-clickfirstButtonto create an event handler procedure.
Add code to thefirstButton_Clickevent handler to callHandleButtons.
Follow the same steps to add code for the other three navigation buttons.
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
Open the Ribbon1.xml file.
Within the group node, add the markup for a toggle button to open and close the custom task pane. If you still have the originaltoggleButton1markup in the XML file, replace it with this XML content.
Before you can use a custom task pane, you need to add it to theCustomTaskPanescollection 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.
TheCustomTaskPaneclass is in theMicrosoft.Office.Toolsnamespace, so add a statement to the top of the file to import the namespace.
Within the class, add a public variable that refers to custom task pane.
Modify theThisAddIn_Startupprocedure by adding an instance of the user control to theCustomTaskPanescollection.
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;}
Open theRibbon1.vbfile and add theHandleTaskPaneprocedure to theRibbon1class to toggle the visibility of the task pane.
Save and run your add-in. In PowerPoint, click the newCommon Taskstab to see the toggle button on the Office Fluent Ribbon.
Click theNavigation Panetoggle button. You see the navigation task pane, as shown in Figure 4.
Figure 4. The Navigation Task Pane in PowerPointAdd several slides to the active presentation, or open any presentation.
Use the navigation buttons to move between the slides.
Click theNavigation Panetoggle button to hide the custom task pane.
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 itsClosebutton. 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
In PowerPoint, click theNavigation Panetoggle button to show the task pane.
Click theClosebutton on the task pane to close it.
Notice that the toggle button remains selected, even though the task pane is now hidden.
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 aToggleButtoncontrol, you can specify thegetPressedattribute. 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 returnsTrueto indicate that it is pressed andFalseto indicate that it is not.
To determine the pressed state of the ToggleButton control
In theRibbon1class, add a public procedure that allows code in the add-in class to force the Office Fluent Ribbon to refresh. This code calls theInvalidateControlmethod for the Office Fluent Ribbon, which forces the specified control to refresh its display.
In theRibbon1class, add the status callback that determines the state of the toggle button, based on the visibility of the custom task pane.
In Ribbon1.xml, add support for retrieving the pressed state of the button by calling theGetPressedmethod you just created. Modify the XML markup for the toggle button by adding thegetPressedattribute, so that it looks like this.
In theThisAddInclass in the Ribbon1.vb file, add support for handling theVisibleChangedevent for the task pane. Add this event handler to the class, which calls theRefreshmethod for the Ribbon1 class and updates the pressed state of the toggle button when the visibility changes.
Finally, modify the existingStartupandShutdownprocedures in the ThisAddIn.vb file, hooking and unhooking theVisibleChangedevent on the task pane.
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);}
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.
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 theOffice 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-authoredAppDev'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 authoredAppDev’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
'기타' 카테고리의 다른 글
How to: Get All the Text in a Slide in a Presentation (0) | 2011.04.06 |
---|---|
SlideClass.NotesPage Property (0) | 2011.04.06 |
2007 Office Fluent Ribbon을 사용자 지정 (개발자 대상) (3부) (0) | 2011.04.05 |
2007 Office Fluent Ribbon을 사용자 지정 (개발자 대상) (2부) (0) | 2011.04.05 |
2007 Office Fluent Ribbon을 사용자 지정 (개발자 대상) (1부) (0) | 2011.04.05 |