Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS Word Add-in: RIght click handler

Tags:

c#

ms-word

add-in

I am developing an Add-in for MS Word 2010 and I want to add a couple of menu items to the right click menu (only when some text is selected). I have seen a couple of examples to add items but couldn't find how to add items conditionally. In short I want to override something like OnRightClick handler. Thanks in advance.

like image 688
Mujtaba Hassan Avatar asked Jan 15 '23 21:01

Mujtaba Hassan


1 Answers

This is quite simple, you need to handle the WindowBeforeRightClick event. Inside the event locate the required command bar and the specfic control and handle either the Visible or the Enabled property.

In the example below I toggle the Visible property of a custom button created on the Text command bar based on the selection(If selection contains "C#" hide the button otherwise show it)

    //using Word = Microsoft.Office.Interop.Word;
    //using Office = Microsoft.Office.Core;

    Word.Application application;

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        application = this.Application;
        application.WindowBeforeRightClick +=
            new Word.ApplicationEvents4_WindowBeforeRightClickEventHandler(application_WindowBeforeRightClick);

        application.CustomizationContext = application.ActiveDocument;

        Office.CommandBar commandBar = application.CommandBars["Text"];
        Office.CommandBarButton button = (Office.CommandBarButton)commandBar.Controls.Add(
            Office.MsoControlType.msoControlButton);
        button.accName = "My Custom Button";
        button.Caption = "My Custom Button";
    }

    public void application_WindowBeforeRightClick(Word.Selection selection, ref bool Cancel)
    {
        if (selection != null && !String.IsNullOrEmpty(selection.Text))
        {
            string selectionText = selection.Text;

            if (selectionText.Contains("C#"))
                SetCommandVisibility("My Custom Button", false);
            else
                SetCommandVisibility("My Custom Button", true);
        }
    }

    private void SetCommandVisibility(string name, bool visible)
    {
        application.CustomizationContext = application.ActiveDocument;
        Office.CommandBar commandBar = application.CommandBars["Text"];
        commandBar.Controls[name].Visible = visible;
    }
like image 198
Denys Wessels Avatar answered Jan 23 '23 03:01

Denys Wessels