且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Microsoft Office Word 中添加菜单项

更新时间:2023-02-08 09:33:31

OK, Finally I have successed to fix it.

first of all, there are more than 200 different contextmenu for RightClick

but the common type of word.application.CommandBars are base on under Indexes { 105, 120, 127, 117, 108, 99, 134 }; these are contains the indexes of text, table, heading, textBox and ...

so, you must update your code by foreach to iterate the create new commandBarButtons on each type of ContextMenu someting like under code use this on your Startup Function

                try
                {


                    List<int> mindex = new List<int>() { 105, 120, 127, 117, 108, 99, 134 };
                    foreach (var item in mindex)
                    {

                        AddItemGeneral(applicationObject.CommandBars[item], youreventHandler, "yourTagLabelplusaDiffNumber" + item.ToString(), "your Caption");                            
                    }



                }
                catch (Exception exception)
                {
                    MessageBox.Show("Error: " + exception.Message);
                }

Finally,

private void AddItemGeneral(CommandBar popupCommandBar, _CommandBarButtonEvents_ClickEventHandler MyEvent, string MyTag,string MyCaption)
{

    CommandBarButton commandBarButton = popupCommandBar.CommandBars.FindControl(MsoControlType.msoControlButton, missing, MyTag, missing) as CommandBarButton;          
    if (commandBarButton == null)
    {

        commandBarButton = (CommandBarButton)popupCommandBar.Controls.Add(MsoControlType.msoControlButton, Missing.Value, Missing.Value, popupCommandBar.Controls.Count + 1, true);
        commandBarButton.Caption = MyCaption;
        commandBarButton.BeginGroup = true;
        commandBarButton.Tag = MyTag;
        commandBarButton.Click += MyEvent;
    }
    else
    {
        commandBarButton.Click += MyEvent;
    }

}

I hope it helps you guys. ;->