Walkthrough: Adding Controls to a Document at Run Time in an Application-Level Add-In

Applies to

The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office.

Project type

  • Application-level projects

Microsoft Office version

  • Word 2007

For more information, see Features Available by Application and Project Type.

Starting in Visual Studio 2008 Service Pack 1 (SP1), you can add controls to any open Microsoft Office Word 2007 document by using an application-level add-in. This walkthrough demonstrates how to use the Ribbon to enable users to add a Button or a RichTextContentControl to a document.

This walkthrough illustrates the following tasks:

  • Creating a new Word 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 Visual Studio Settings.

Prerequisites

You need the following components to complete this walkthrough:

  • Visual Studio Tools for Office (an optional component of Visual Studio 2008 Professional and Visual Studio Team System).

  • Visual Studio 2008 SP1.

  • Microsoft Office Word 2007.

Creating a New Word Add-in Project

Start by creating a Word 2007 add-in project.

To create a new Word add-in project

Providing 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

    addButtonComboBox

    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.

Adding and Removing Controls on the Active Document

In the add-in code, you must convert the active document into a Microsoft.Office.Tools.Word.Documenthost item before you can add a control. In Visual Studio Tools for Office solutions, managed controls can be added only to host items, which act as containers for the controls. In application-level add-in projects, host items can be created only 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 button As Microsoft.Office.Tools.Word.Controls.Button = Nothing 
    Private richTextControl As RichTextContentControl = Nothing
    
    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.

    Friend Sub ToggleButtonOnDocument()
        Dim nativeDocument As Word.Document = Me.Application.ActiveDocument
        Dim vstoDocument As Document = nativeDocument.GetVstoObject()
        Dim name As String = "MyButton" 
    
        If Globals.Ribbons.MyRibbon.addButtonCheckBox.Checked Then 
            Dim selection = Me.Application.Selection
            If selection IsNot Nothing AndAlso selection.Range IsNot Nothing Then
                button = vstoDocument.Controls.AddButton( _
                    selection.Range, 100, 30, name)
            End If 
        Else
            vstoDocument.Controls.Remove(name)
        End If 
    End Sub
    
    internal void ToggleButtonOnDocument()
    {
        Word.Document nativeDocument = this.Application.ActiveDocument;
        Document vstoDocument = nativeDocument.GetVstoObject();
        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.

    Friend Sub ToggleRichTextControlOnDocument()
        Dim nativeDocument As Word.Document = Me.Application.ActiveDocument
        Dim vstoDocument As Document = nativeDocument.GetVstoObject()
        Dim name As String = "MyRichTextBoxControl" 
    
        If Globals.Ribbons.MyRibbon.addRichTextCheckBox.Checked Then 
            Dim selection = Me.Application.Selection
            If selection IsNot Nothing AndAlso selection.Range IsNot Nothing Then
                richTextControl = vstoDocument.Controls.AddRichTextContentControl( _
                        selection.Range, name)
            End If 
        Else
            vstoDocument.Controls.Remove(name)
        End If 
    End Sub
    
    internal void ToggleRichTextControlOnDocument()
    {
        Word.Document nativeDocument = this.Application.ActiveDocument;
        Document vstoDocument = nativeDocument.GetVstoObject();
        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);
        }
    }
    

Removing 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 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 Sub Application_DocumentBeforeSave(ByVal Doc As Word.Document, _
        ByRef SaveAsUI As Boolean, ByRef Cancel As Boolean) Handles Application.DocumentBeforeSave
        If Doc.HasVstoObject() Then 
            Dim vstoDocument As Document = Doc.GetVstoObject()
            If vstoDocument.Controls.Contains(button) Then
                vstoDocument.Controls.Remove(button)
                Globals.Ribbons.MyRibbon.addButtonCheckBox.Checked = False 
            End If 
        End If 
    End Sub
    
    private void Application_DocumentBeforeSave(Word.Document Doc, 
        ref bool SaveAsUI, ref bool Cancel)
    {
        if (Doc.HasVstoObject())
        {
            Document vstoDocument = Doc.GetVstoObject();
    
            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);
    

Adding and Removing 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

  • 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 Sub addButtonCheckBox_Click(ByVal sender As System.Object, _
        ByVal e As RibbonControlEventArgs) Handles addButtonCheckBox.Click
        Globals.ThisAddIn.ToggleButtonOnDocument()
    End Sub 
    
    Private Sub addRichTextCheckBox_Click(ByVal sender As System.Object, _
        ByVal e As RibbonControlEventArgs) Handles addRichTextCheckBox.Click
        Globals.ThisAddIn.ToggleRichTextControlOnDocument()
    End Sub
    
    private void addButtonCheckBox_Click(object sender, RibbonControlEventArgs e)
    {
        Globals.ThisAddIn.ToggleButtonOnDocument();
    }
    
    private void addRichTextCheckBox_Click(object sender, RibbonControlEventArgs e)
    {
        Globals.ThisAddIn.ToggleRichTextControlOnDocument();
    }
    

Testing 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 application-level add-ins from these topics:

See Also

Tasks

How to: Add Windows Forms Controls to Office Documents

How to: Add Content Controls to Word Documents

Word Add-In Dynamic Controls Sample

Concepts

Word Application-Level Add-in Development

Adding Controls to Office Documents at Run Time

Persisting Dynamic Controls in Office Documents

Extending Word Documents and Excel Workbooks in Application-Level Add-ins at Run Time

Change History

Date

History

Reason

July 2008

Added topic.

SP1 feature change.