Search code examples
c#office-interopoffice-addins

"Text" CommandBar not always present in Microsoft Word


I am building a C# Add-In for Microsoft Word. My goal is to add a button in the right click menu. It is easy to add a CommandBarButton in the "Text" CommandBar.

    Word.Application application;
    Office.CommandBar textCommandBar;
    Office.CommandBarButton myButton;

    private void InitContextMenuButton()
    {
        application.CustomizationContext = application.ActiveDocument;
        textCommandBar = application.CommandBars["Text"];
        myButton= textCommandBar.Controls.Add(Office.MsoControlType.msoControlButton, 1, "My Custom Button", 1, false) 
            as Office.CommandBarButton;
        myButton.Tag = "My Custom Button";
        myButton.accName = "My Custom Button";
        myButton.Caption = "My Custom Button";
        myButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(Button_Click);
        myButton.Visible = true;
    }

This work pretty well most of the time.

enter image description here

My issue is that sometime the button is not always there. Sometime, when I click on list or a table, the "Text" CommandBar seems to not present in the context menu.

enter image description here


Solution

  • The context menus are, after all CONTEXT menus: they change depending on where the right-click is made. The "Text" menu is only for "plain text" contexts. When the right-click is in a Table cell there's a different menu for that. Or if spelling/grammar errors are marked, you get yet a different menu.

    So you need to determine in which contexts your button should appear and add it to ALL those context menus.

    Please also note that, since version 2010 you should NOT be doing this using the CommandBars object. You should define Ribbon XML for this purpose.