Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add a Menu Item in Microsoft Office Word

Tags:

c#

ms-word

vsto

I tried to create a right-click menu item in Microsoft Word based on this post.

Here is my code:

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        try
        {
            eventHandler = new _CommandBarButtonEvents_ClickEventHandler(MyButton_Click);
            Word.Application applicationObject = Globals.ThisAddIn.Application as Word.Application;
            applicationObject.WindowBeforeRightClick += new Microsoft.Office.Interop.Word.ApplicationEvents4_WindowBeforeRightClickEventHandler(App_WindowBeforeRightClick);
        }
        catch (Exception exception)
        {
            MessageBox.Show("Error: " + exception.Message);
        }
    }

    void App_WindowBeforeRightClick(Microsoft.Office.Interop.Word.Selection Sel, ref bool Cancel)
    {
        try
        {
            this.AddItem();
        }
        catch (Exception exception)
        {
            MessageBox.Show("Error: " + exception.Message);
        }

    }
    private void AddItem()
    {
        Word.Application applicationObject = Globals.ThisAddIn.Application as Word.Application;
        CommandBarButton commandBarButton = applicationObject.CommandBars.FindControl(MsoControlType.msoControlButton, missing, "HELLO_TAG", missing) as CommandBarButton;
        if (commandBarButton != null)
        {
            System.Diagnostics.Debug.WriteLine("Found button, attaching handler");
            commandBarButton.Click += eventHandler;
            return;
        }
        CommandBar popupCommandBar = applicationObject.CommandBars["Text"];
        bool isFound = false;
        foreach (object _object in popupCommandBar.Controls)
        {
            CommandBarButton _commandBarButton = _object as CommandBarButton;
            if (_commandBarButton == null) continue;
            if (_commandBarButton.Tag.Equals("HELLO_TAG"))
            {
                isFound = true;
                System.Diagnostics.Debug.WriteLine("Found existing button. Will attach a handler.");
                commandBarButton.Click += eventHandler;
                break;
            }
        }
        if (!isFound)
        {
            commandBarButton = (CommandBarButton)popupCommandBar.Controls.Add(MsoControlType.msoControlButton, missing, missing, missing, true);
            System.Diagnostics.Debug.WriteLine("Created new button, adding handler");
            commandBarButton.Click += eventHandler;
            commandBarButton.Caption = "h5";
            commandBarButton.FaceId = 356;
            commandBarButton.Tag = "HELLO_TAG";
            commandBarButton.BeginGroup = true;
        }
    }

    private void RemoveItem()
    {
        Word.Application applicationObject = Globals.ThisAddIn.Application as Word.Application;
        CommandBar popupCommandBar = applicationObject.CommandBars["Text"];
        foreach (object _object in popupCommandBar.Controls)
        {
            CommandBarButton commandBarButton = _object as CommandBarButton;
            if (commandBarButton == null) continue;
            if (commandBarButton.Tag.Equals("HELLO_TAG"))
            {
                popupCommandBar.Reset();
            }
        }
    }
    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
        Word.Application App = Globals.ThisAddIn.Application as Word.Application;
        App.WindowBeforeRightClick -= new Microsoft.Office.Interop.Word.ApplicationEvents4_WindowBeforeRightClickEventHandler(App_WindowBeforeRightClick);

    }

    #region VSTO generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }
    #endregion
    //Event Handler for the button click

    private void MyButton_Click(CommandBarButton cmdBarbutton, ref bool cancel)
    {
        System.Windows.Forms.MessageBox.Show("Hello !!! Happy Programming", "l19 !!!");
        RemoveItem();
    }
}

}

and the result when i right click on a letter :

enter image description here

But with a table I cannot do it. Check out the screenshot to see what I mean:

enter image description here

I can not add the item menu when i right click on a table of ms word. Please help me. Thank!!

sorry about my english,...

like image 857
Quang Avatar asked Dec 15 '15 02:12

Quang


People also ask

How do you insert a menu in Word?

On the toolbar ribbon, select References. Near the left end, select Insert Table of Contents. (Or select Table of Contents > Insert Table of Contents. The table of contents is inserted, showing the headings and page numbering in your document.

Which is a menu item in Word?

The Menu bar is directly below the Title bar and it displays the menu. The menu begins with the word File and continues with Edit, View, Insert, Format, Tools, Table, Window, and Help. You use the menu to give instructions to the software.


1 Answers

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"]);
like image 103
Dirk Vollmar Avatar answered Oct 31 '22 22:10

Dirk Vollmar