Walkthrough: Creating Shortcut Menus for Bookmarks

This walkthrough demonstrates how to create shortcut menus for Bookmark controls in a document-level customization for Word. When a user right-clicks the text in a bookmark, a shortcut menu appears and gives the user options for formatting the text.

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

This walkthrough illustrates the following tasks:

  • Adding text and bookmarks to the document in a document-level project at design time.

  • Creating a shortcut menu.

  • Checking for overlapping bookmarks.

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:

-

An edition of Visual Studio 2010 that includes the Microsoft Office developer tools. For more information, see [Configuring a Computer to Develop Office Solutions](bb398242\(v=vs.100\).md).
  • Microsoft Office Word 2007 or Word 2010.

Creating the Project

The first step is to create a Word document project in Visual Studio.

To create a new project

  • Create a Word document project that has the name My Bookmark Shortcut Menu. In the wizard, select Create a new document. For more information, see How to: Create Office Projects in Visual Studio.

    Visual Studio opens the new Word document in the designer and adds the My Bookmark Shortcut Menu project to Solution Explorer.

Adding Text and Bookmarks to the Document

Add some text to your document and then add two overlapping bookmarks.

To add text to your document

  • Type the following text.

    This is an example of creating a shortcut menu when you right-click the text in a bookmark.

To add a Bookmark control to your document

  1. From the Word Controls tab of the Toolbox, drag a Bookmark control to your document.

    The Add Bookmark Control dialog box appears.

  2. Select the words creating a shortcut menu when you right-click the text and then click OK.

    bookmark1 is added to the document.

  3. Add another Bookmark control to the words right-click the text in a bookmark.

    bookmark2 is added to the document.

    Note

    The words right-click the text are in both bookmark1 and bookmark2.

When you add a bookmark to a document at design time, a Bookmark control is created. You can program against several events of the bookmark. You can write code in the BeforeRightClick event of the bookmark so that when the user right-clicks the text in the bookmark, a shortcut menu appears.

Creating the Short Menu

To create the shortcut menu

  1. In Solution Explorer, right-click ThisDocument, and then click View Code.

  2. Declare the CommandBar variables and a bookmark variable at the class level.

    Private commandBar As Office.CommandBar
    Private selectedBookmark As Microsoft.Office.Tools.Word.Bookmark
    WithEvents boldText As Office.CommandBarButton
    WithEvents ItalicText As Office.CommandBarButton
    
    private Office.CommandBar commandBar;
    private Office.CommandBarButton boldText;
    private Office.CommandBarButton italicText;
    private Microsoft.Office.Tools.Word.Bookmark selectedBookmark;
    
    const int WordTrue = -1;
    const int WordFalse = 0;
    
  3. Add a method to create the menu.

    Private Sub AddPopUp()
    
        commandBar = Application.CommandBars.Add( _
            "FormatText", Office.MsoBarPosition.msoBarPopup, , True)
    
        ' Add a button and set the style, caption, icon and tag.
        boldText = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
    
        With boldText
            .Style = Office.MsoButtonStyle.msoButtonIconAndCaption
            .Caption = "Bold"
            .FaceId = 113
            .Tag = "0"
        End With
    
        ' Add a button and set the style, caption, icon and tag.
        ItalicText = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
    
        With ItalicText
            .Style = Office.MsoButtonStyle.msoButtonIconAndCaption
            .Caption = "Italic"
            .FaceId = 114
            .Tag = "1"
        End With
    
        CType(Me.AttachedTemplate, Microsoft.Office.Interop.Word.Template).Saved = True
    
    End Sub
    
    private void AddPopUp()
    {
        commandBar = Application.CommandBars.Add("FormatText",
            Office.MsoBarPosition.msoBarPopup, missing, true);
    
        // Add a button and set the style, caption, icon and tag.
        boldText = (Office.CommandBarButton)commandBar.Controls.Add(
            1, missing, missing, missing, missing);
    
        boldText.Style = Office.MsoButtonStyle.msoButtonCaption;
        boldText.Caption = "Bold";
        boldText.FaceId = 113;
        boldText.Tag = "0";
    
        // Add a button and set the style, caption, icon and tag.
        italicText = (Office.CommandBarButton)commandBar.Controls.Add(
            1, missing, missing, missing, missing);
    
        italicText.Style = Office.MsoButtonStyle.msoButtonCaption;
        italicText.Caption = "Italic";
        italicText.FaceId = 114;
        italicText.Tag = "1";
    
        // Handle the click events with the ButtonClick procedure.
        boldText.Click +=
            new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(ButtonClick);
    
        italicText.Click +=
            new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(ButtonClick);
    
        ((Microsoft.Office.Interop.Word.Template)this.AttachedTemplate).Saved = true;
    }
    
  4. Call AddPopup from the Startup event of ThisDocument.

    Private Sub ThisDocument_Startup(ByVal sender As Object, ByVal e As _
        System.EventArgs) Handles Me.Startup
    
        AddPopUp()
    End Sub
    
    private void ThisDocument_Startup(object sender, System.EventArgs e)
    {
        AddPopUp();
    }
    

To format the text in the bookmark

  1. Add a ButtonClick event handler to apply formatting to the bookmark.

    Private Sub ButtonClick(ByVal ctrl As Office.CommandBarButton, _
        ByRef Cancel As Boolean) Handles boldText.Click, ItalicText.Click
    
        Select Case ctrl.Caption
            Case "Bold"
                selectedBookmark.Bold = Not selectedBookmark.Bold
            Case "Italic"
                selectedBookmark.Italic = Not selectedBookmark.Italic
        End Select
    
        Me.ActiveWindow.SetFocus()
    End Sub
    
    private void ButtonClick(Microsoft.Office.Core.CommandBarButton Ctrl,
        ref bool CancelDefault)
    {
        if (Ctrl.Caption == "Bold")
        {
            if (selectedBookmark.Bold == WordTrue)
            {
                selectedBookmark.Bold = WordFalse;
            }
            else
            {
                selectedBookmark.Bold = WordTrue;
            }
        }
        else if (Ctrl.Caption == "Italic")
        {
            if (selectedBookmark.Italic == WordTrue)
            {
                selectedBookmark.Italic = WordFalse;
            }
            else
            {
                selectedBookmark.Italic = WordTrue;
            }
        }
    }
    
  2. Add a showPopupMenu event handler to handle the BeforeRightClick event of both bookmarks.

    Note

    You must write code to handle the case where bookmarks overlap. If you do not, by default, the code will be called for all bookmarks in the selection.

    Private Sub showPopupMenu(ByVal sender As Object, ByVal e _
        As Microsoft.Office.Tools.Word.ClickEventArgs) _
        Handles Bookmark1.BeforeRightClick, Bookmark2.BeforeRightClick
    
        Dim startPosition As Integer = 0
        Dim i As Integer
    
        ' If bookmarks overlap, get bookmark closest to cursor.
        For i = 1 To e.Selection.Bookmarks.Count
            If e.Selection.Bookmarks(i).Start > startPosition Then
                startPosition = e.Selection.Bookmarks(i).Start
            End If
        Next
    
        ' If closest bookmark is the sender, show the popup.
        If DirectCast(sender, Microsoft.Office.Tools.Word.Bookmark).Start = _
            startPosition Then
            selectedBookmark = DirectCast(sender, Microsoft.Office.Tools.Word.Bookmark)
            commandBar.ShowPopup()
            e.Cancel = True
        End If
    End Sub
    
    private void ShowPopupMenu(object sender,
        Microsoft.Office.Tools.Word.ClickEventArgs e)
    {
        int startPosition = 0;
    
        // If bookmarks overlap, get bookmark closest to cursor.
        for (int i = 1; i <= e.Selection.Bookmarks.Count; i++)
        {
            if (e.Selection.Bookmarks[i].Start > startPosition)
            {
                startPosition = e.Selection.Bookmarks[i].Start;
            }
        }
    
        // If closest bookmark is the sender, show the popup.
        if (((Microsoft.Office.Tools.Word.Bookmark)sender).Start == startPosition)
        {
            selectedBookmark = (Microsoft.Office.Tools.Word.Bookmark)sender;
            commandBar.ShowPopup(missing, missing);
            e.Cancel = true;
        }
    }
    
  3. In C#, you must add event handlers for the bookmark controls to the Startup event. For information about creating event handlers, see How to: Create Event Handlers in Office Projects.

    this.bookmark1.BeforeRightClick +=
        new Microsoft.Office.Tools.Word.ClickEventHandler(ShowPopupMenu);
    
    this.bookmark2.BeforeRightClick +=
        new Microsoft.Office.Tools.Word.ClickEventHandler(ShowPopupMenu);
    

Testing the Application

Test your document to verify that the bold and italic menu items appear in the shortcut menu when you right-click text in a bookmark, and that the text is properly formatted.

To test your document

  1. Press F5 to run your project.

  2. Right-click in the first bookmark, and then click Bold.

  3. Verify that all of the text in bookmark1 is formatted as bold.

  4. Right-click the text where the bookmarks overlap, and then click Italic.

  5. Verify that all of the text in bookmark2 is italic, and only the part of the text in bookmark1 that overlaps bookmark2 is italic.

Next Steps

Here are some tasks that might come next:

See Also

Concepts

Walkthroughs Using Word

Automating Word by Using Extended Objects

Bookmark Control

Optional Parameters in Office Solutions

Other Resources

Office UI Customization