Partager via


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 2013 and Word 2010. For more information, see Features Available by Office Application and Project Type.

This walkthrough illustrates the following tasks:

  • Creating a Word document project in Visual Studio.

  • 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 Customizing Development Settings in Visual Studio.

Prerequisites

You need the following components to complete this walkthrough:

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

  • In the document that appears in the designer of your project, 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. In the Toolbox, from the Word Controls tab, 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.

Adding Commands to a Shortcut Menu

Add buttons to the shortcut menu that appears when you right-click the document.

To add commands to a shortcut menu

  1. Add a Ribbon XML item to the project. For more information, see How to: Get Started Customizing the Ribbon.

  2. In Solution Explorer, select ThisDocument.cs or ThisDocument.vb.

  3. On the menu bar, choose View, Code.

    The ThisDocument class file opens in the Code Editor.

  4. Add the following code to the ThisDocument class. This code overrides the CreateRibbonExtensibilityObject method and returns the Ribbon XML class to the Office application.

    Protected Overrides Function CreateRibbonExtensibilityObject() As Microsoft.Office.Core.IRibbonExtensibility
        Return New Ribbon1()
    End Function
    
    protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
    {
        return new Ribbon1();
    }
    
  5. In Solution Explorer, select the Ribbon XML file. By default, the Ribbon XML file is named Ribbon1.xml.

  6. On the menu bar, choose View, Code.

    The Ribbon xml file opens in the Code Editor.

  7. In the Code Editor, replace the contents of the Ribbon XML file with the following code.

    <?xml version="1.0" encoding="UTF-8"?>
    <customUI xmlns="https://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load">
      <contextMenus>
        <contextMenu idMso="ContextMenuText">
          <button id="BoldButton" label="Bold" onAction="ButtonClick"        
               getVisible="GetVisible" />
          <button id="ItalicButton" label="Italic" onAction="ButtonClick" 
              getVisible="GetVisible"/>
        </contextMenu>
      </contextMenus>
    </customUI>
    

    This code adds two buttons to the shortcut menu that appears when you right-click the document.

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

  9. Declare the following variables and a bookmark variable at the class level.

    Public selectedBookmark As Microsoft.Office.Tools.Word.Bookmark
    Public ShowBoldButton As String = False 
    Public ShowItalicButton As String = False 
    Public WordTrue As Integer = -1
    Public WordFalse As Integer = 0
    
    public Microsoft.Office.Tools.Word.Bookmark selectedBookmark;
            public bool showBoldButton = false;
            public bool showItalicButton = false;
            public int WordTrue = -1;
            public int WordFalse = 0;
    
  10. In Solution Explorer, select the Ribbon code file. By default, the Ribbon code file is named Ribbon1.cs or Ribbon1.vb.

  11. On the menu bar, choose View, Code.

    The Ribbon code file opens in the Code Editor.

  12. In the Ribbon code file, add the following method. This is a callback method for the two buttons that you have added to the shortcut menu of the document. This method determines whether these buttons appear in the shortcut menu. The bold and italic buttons appear only if you right-click text within the bookmark.

    Public Function GetVisible(ByVal control As Office.IRibbonControl) As Boolean 
        If control.Id = "BoldButton" Then 
            If Globals.ThisDocument.ShowBoldButton = True Then
                Globals.ThisDocument.ShowBoldButton = False 
                Return True 
            Else 
                Return False 
            End If 
        ElseIf control.Id = "ItalicButton" Then 
            If Globals.ThisDocument.ShowItalicButton = True Then
                Globals.ThisDocument.ShowItalicButton = False 
                Return True 
            Else 
                Return False 
            End If 
        Else 
            Return False 
        End If 
    End Function
    
    public bool GetVisible(Office.IRibbonControl control)
           {
               if (control.Id == "BoldButton")
               {
                   if (Globals.ThisDocument.showBoldButton == true)
                   {
                       Globals.ThisDocument.showBoldButton = false;
                       return true;
                   }
                   else
                   {
                       return false;
                   }
               }
               else if (control.Id == "ItalicButton")
               {
                   if (Globals.ThisDocument.showItalicButton == true)
                   {
                       Globals.ThisDocument.showItalicButton = false;
                       return true;
                   }
                   else
                   {
                       return false;
                   }
               }
               else
               {
                   return false;
               }
    
           }
    

Format the Text in the Bookmark

To format the text in the bookmark

  1. In the Ribbon code file, add a ButtonClick event handler to apply formatting to the bookmark.

    Public Sub ButtonClick(ByVal control As Office.IRibbonControl)
        If control.Id = "BoldButton" Then 
            If Globals.ThisDocument.selectedBookmark.Bold = _
                Globals.ThisDocument.WordTrue Then
                Globals.ThisDocument.selectedBookmark.Bold = _
                    Globals.ThisDocument.WordFalse
            Else
                Globals.ThisDocument.selectedBookmark.Bold = _
                    Globals.ThisDocument.WordTrue
            End If 
        ElseIf control.Id = "ItalicButton" Then 
            If Globals.ThisDocument.selectedBookmark.Italic = _
                Globals.ThisDocument.WordTrue Then
                Globals.ThisDocument.selectedBookmark.Italic = _
                    Globals.ThisDocument.WordFalse
            Else
                Globals.ThisDocument.selectedBookmark.Italic = _
                    Globals.ThisDocument.WordTrue
            End If 
        End If 
    End Sub
    
    public void ButtonClick(Office.IRibbonControl control)
    {
        if (control.Id == "BoldButton")
        {
            if (Globals.ThisDocument.selectedBookmark.Bold == 
                Globals.ThisDocument.WordTrue)
            {
                Globals.ThisDocument.selectedBookmark.Bold = 
                    Globals.ThisDocument.WordFalse;
            }
            else
            {
                Globals.ThisDocument.selectedBookmark.Bold = 
                    Globals.ThisDocument.WordTrue;
            }
        }
        else if (control.Id == "ItalicButton")
        {
            if (Globals.ThisDocument.selectedBookmark.Italic == 
                Globals.ThisDocument.WordTrue)
            {
                Globals.ThisDocument.selectedBookmark.Italic = 
                    Globals.ThisDocument.WordFalse;
            }
            else
            {
                Globals.ThisDocument.selectedBookmark.Italic = 
                    Globals.ThisDocument.WordTrue;
            }
        }
    
    }
    
  2. Solution Explorer, select ThisDocument.cs or ThisDocument.vb.

  3. On the menu bar, choose View, Code.

    The ThisDocument class file opens in the Code Editor.

  4. Add the following code to the ThisDocument class.

    Private Sub Bookmark_BeforeRightClick(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 shortcut menu options. 
        If DirectCast(sender, Microsoft.Office.Tools.Word.Bookmark).Start = _
            startPosition Then
            selectedBookmark = DirectCast(sender, Microsoft.Office.Tools.Word.Bookmark)
    
            ShowBoldButton = True
            ShowItalicButton = True 
    
        End If 
    
    End Sub
    
    void bookmark_BeforeRightClick(object sender, 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 shortcut menu options. 
                if (((Microsoft.Office.Tools.Word.Bookmark)sender).Start == startPosition)
                {
                    selectedBookmark = (Microsoft.Office.Tools.Word.Bookmark)sender;
    
                    showBoldButton = true;
                    showItalicButton = true;
    
                }
    
            }
    

    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.

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

    private void ThisDocument_Startup(object sender, System.EventArgs e)
    {
        this.bookmark1.BeforeRightClick += new ClickEventHandler(bookmark_BeforeRightClick);
        this.bookmark2.BeforeRightClick += new ClickEventHandler(bookmark_BeforeRightClick);
    }
    

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