Edit

Share via


Walkthrough: Add controls to a document at run time in a VSTO Add-in

You can add controls to any open Microsoft Office Word document by using a VSTO Add-in. This walkthrough demonstrates how to use the ribbon to enable users to add a Button or a RichTextContentControl to a document.

Applies to: The information in this topic applies to VSTO Add-in projects for Word 2010. For more information, see Features Available by Office Application and Project Type.

This walkthrough illustrates the following tasks:

  • Creating a new Word VSTO Add-in project.

  • Providing a user interface (UI) to add controls to the document.

  • Adding controls to the document at run time.

  • Removing controls from the document.

    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 IDE.

Prerequisites

You need the following components to complete this walkthrough:

Create a new Word Add-in project

Start by creating a Word VSTO Add-in project.

To create a new Word VSTO Add-in project

  1. Create a VSTO Add-in project for Word with the name WordDynamicControls. For more information, see How to: Create Office projects in Visual Studio.

  2. Add a reference to the Microsoft.Office.Tools.Word.v4.0.Utilities.dll assembly. This reference is required to programmatically add a Windows Forms control to the document later in this walkthrough.

Provide a UI to add controls to a document

Add a custom tab to the Ribbon in Word. Users can select check boxes on the tab to add controls to a document.

To provide a UI to add controls to a document

  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 MyRibbon, and click Add.

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

  4. In the Ribbon Designer, click the group1 group.

  5. In the Properties window, change the Label property for group1 to Add Controls.

  6. From the Office Ribbon Controls tab of the Toolbox, drag a CheckBox control onto group1.

  7. Click CheckBox1 to select it.

  8. In the Properties window, change the following properties.

    Property Value
    Name addButtonCheckBox
    Label Add Button
  9. Add a second check box to group1, and then change the following properties.

    Property Value
    Name addRichTextCheckBox
    Label Add Rich Text Control
  10. In the Ribbon Designer, double-click Add Button.

    The Click event handler of the Add Button check box opens in the Code Editor.

  11. Return to the Ribbon Designer, and double-click Add Rich Text Control.

    The Click event handler of the Add Rich Text Control check box opens in the Code Editor.

    Later in this walkthrough, you will add code to these event handlers to add and remove controls on the active document.

Add and remove controls on the active document

In the VSTO Add-in code, you must convert the active document into a Documenthost item before you can add a control. In Office solutions, managed controls can be added only to host items, which act as containers for the controls. In VSTO Add-in projects, host items can be created at run time by using the GetVstoObject method.

Add methods to the ThisAddIn class that can be called to add or remove a Button or RichTextContentControl on the active document. Later in this walkthrough, you will call these methods from the Click event handlers of the check boxes on the Ribbon.

To add and remove controls on the active document

  1. In Solution Explorer, double-click ThisAddIn.cs or ThisAddIn.vb to open the file in the Code Editor.

  2. Add the following code to the ThisAddIn class. This code declares Button and RichTextContentControl objects that represent the controls that will be added to the document.

    private Microsoft.Office.Tools.Word.Controls.Button button = null;
    private RichTextContentControl richTextControl = null;
    
  3. Add the following method to the ThisAddIn class. When the user clicks the Add Button check box on the Ribbon, this method adds a Button to the current selection on the document if the check box is selected, or removes the Button if the check box is cleared.

    internal void ToggleButtonOnDocument()
    {
        Document vstoDocument = Globals.Factory.GetVstoObject(this.Application.ActiveDocument);
    
    
        string name = "MyButton";
    
        if (Globals.Ribbons.MyRibbon.addButtonCheckBox.Checked)
        {
            Word.Selection selection = this.Application.Selection;
            if (selection != null && selection.Range != null)
            {
                button = vstoDocument.Controls.AddButton(
                    selection.Range, 100, 30, name);
            }
        }
        else
        {
            vstoDocument.Controls.Remove(name);
        }
    }
    
  4. Add the following method to the ThisAddIn class. When the user clicks the Add Rich Text Control check box on the Ribbon, this method adds a RichTextContentControl to the current selection on the document if the check box is selected, or removes the RichTextContentControl if the check box is cleared.

    internal void ToggleRichTextControlOnDocument()
    {
    
        Document vstoDocument = Globals.Factory.GetVstoObject(this.Application.ActiveDocument);
    
    
        string name = "MyRichTextBoxControl";
    
        if (Globals.Ribbons.MyRibbon.addRichTextCheckBox.Checked)
        {
            Word.Selection selection = this.Application.Selection;
            if (selection != null && selection.Range != null)
            {
                richTextControl = vstoDocument.Controls.AddRichTextContentControl(
                    selection.Range, name);
            }
        }
        else
        {
            vstoDocument.Controls.Remove(name);
        }
    }
    

Remove the Button control when the document is saved

Windows Forms controls are not persisted when the document is saved and then closed. However, an ActiveX wrapper for each control remains in the document, and the border of this wrapper can be seen by end users when the document is reopened. There are several ways to clean up dynamically created Windows Forms controls in VSTO Add-ins. In this walkthrough, you programmatically remove the Button control when the document is saved.

To remove the Button control when the document is saved

  1. In the ThisAddIn.cs or ThisAddIn.vb code file, add the following method to the ThisAddIn class. This method is an event handler for the DocumentBeforeSave event. If the saved document has a Document host item that is associated with it, the event handler gets the host item and removes the Button control, if it exists.

    private void Application_DocumentBeforeSave(Word.Document Doc, 
        ref bool SaveAsUI, ref bool Cancel)
    {
        bool isExtended = Globals.Factory.HasVstoObject(Doc);
    
    
        if (isExtended)
        {
    
            Microsoft.Office.Tools.Word.Document vstoDocument = Globals.Factory.GetVstoObject(Doc);
    
            if (vstoDocument.Controls.Contains(button))
            {
                vstoDocument.Controls.Remove(button);
                Globals.Ribbons.MyRibbon.addButtonCheckBox.Checked = false;
            }
        }
    }
    
  2. In C#, add the following code to the ThisAddIn_Startup event handler. This code is required in C# to connect the Application_DocumentBeforeSave event handler with the DocumentBeforeSave event.

    this.Application.DocumentBeforeSave += 
        new Word.ApplicationEvents4_DocumentBeforeSaveEventHandler(
        Application_DocumentBeforeSave);
    

Add and remove controls when the user clicks the check boxes on the ribbon

Finally, modify the Click event handlers of the check boxes you added to the ribbon to add or remove controls on the document.

To add or remove controls when the user clicks the check boxes on the ribbon

  1. In the MyRibbon.cs or MyRibbon.vb code file, replace the generated addButtonCheckBox_Click and addRichTextCheckBox_Click event handlers with the following code. This code redefines these event handlers to call the ToggleButtonOnDocument and ToggleRichTextControlOnDocument methods that you added to the ThisAddIn class earlier in this walkthrough.

    private void addButtonCheckBox_Click(object sender, RibbonControlEventArgs e)
    {
        Globals.ThisAddIn.ToggleButtonOnDocument();
    }
    
    private void addRichTextCheckBox_Click(object sender, RibbonControlEventArgs e)
    {
        Globals.ThisAddIn.ToggleRichTextControlOnDocument();
    }
    

Test the solution

Add controls to a document by selecting them from the custom tab on the Ribbon. When you save the document, the Button control is removed.

To test the solution.

  1. Press F5 to run your project.

  2. In the active document, press Enter several times to add new empty paragraphs to the document.

  3. Select the first paragraph.

  4. Click the Add-Ins tab.

  5. In the Add Controls group, click Add Button.

    A button appears in the first paragraph.

  6. Select the last paragraph.

  7. In the Add Controls group, click Add Rich Text Control.

    A rich text content control is added to the last paragraph.

  8. Save the document.

    The button is removed from the document.

Next steps

You can learn more about controls in VSTO Add-ins from these topics: