How to Add a Menu Item in Microsoft Office Word

Word maintains more than one context menu. You can see all of them by enumerating all CommandBar objects in Application.CommandBars whose position is msoBarPopup:

foreach (var commandBar in applicationObject.CommandBars.OfType<CommandBar>()
                               .Where(cb => cb.Position == MsoBarPosition.msoBarPopup))
{
    Debug.WriteLine(commandBar.Name);
}

The command bar that is used in the linked sample is the one named "Text" and this one is related to the context menu that pops up when you right-click somewhere in the text of a paragraph.

However, to add something to the context menu of a table you have to add your button to the appropriate table-related context menu. Tables have a different context menus depending on what is selected when you click:

  • applicationObject.CommandBars["Tables"]
  • applicationObject.CommandBars["Table Text"]
  • applicationObject.CommandBars["Table Cells"]
  • applicationObject.CommandBars["Table Headings"]
  • applicationObject.CommandBars["Table Lists"]
  • applicationObject.CommandBars["Table Pictures"]

So I would suggest that you extract a method that adds a button to a CommandBar and then you call that method with all the command bars where you want to add your button to. Something like the following:

private void AddButton(CommandBar popupCommandBar)
{
    bool isFound = false;
    foreach (var commandBarButton in popupCommandBar.Controls.OfType<CommandBarButton>())
    {
        if (commandBarButton.Tag.Equals("HELLO_TAG"))
        {
            isFound = true;
            Debug.WriteLine("Found existing button. Will attach a handler.");
            commandBarButton.Click += eventHandler;
            break;
        }
    }
    if (!isFound)
    {
        var commandBarButton = (CommandBarButton)popupCommandBar.Controls.Add
            (MsoControlType.msoControlButton, missing, missing, missing, true);
        Debug.WriteLine("Created new button, adding handler");
        commandBarButton.Click += eventHandler;
        commandBarButton.Caption = "Hello !!!";
        commandBarButton.FaceId = 356;
        commandBarButton.Tag = "HELLO_TAG";
        commandBarButton.BeginGroup = true;
    }
}

// add the button to the context menus that you need to support
AddButton(applicationObject.CommandBars["Text"]);
AddButton(applicationObject.CommandBars["Table Text"]);
AddButton(applicationObject.CommandBars["Table Cells"]);

Tags:

C#

Ms Word

Vsto