【问题标题】:How to Add a Menu Item in Microsoft Office Word如何在 Microsoft Office Word 中添加菜单项
【发布时间】:2020-04-27 20:23:44
【问题描述】:

我尝试根据this 帖子在 Microsoft Word 中创建右键菜单项。

这是我的代码:

    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();
    }
}

}

当我右键单击一个字母时的结果:

但是用一张桌子我做不到。查看屏幕截图以了解我的意思:

当我右键单击 ms word 表时,我无法添加项目菜单。请帮我。 谢谢!!

对不起我的英语,...

【问题讨论】:

  • “有一张桌子我做不到”是什么意思?实际发生了什么,您期望什么?你截图中的箭头是什么意思?
  • 我想在右键菜单中添加一个菜单项。有一张桌子我做不到。我想知道在 ms word 2013 中执行此操作的代码。

标签: c# ms-word vsto


【解决方案1】:

Word 维护多个上下文菜单。你可以通过枚举Application.CommandBars中位置为msoBarPopup的所有CommandBar对象来查看它们:

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

链接示例中使用的命令栏是名为“文本”的命令栏,该命令栏与您在段落文本中的某处单击鼠标右键时弹出的上下文菜单有关。

但是,要将某些内容添加到表格的上下文菜单中,您必须将按钮添加到与表格相关的相应上下文菜单中。表格有不同的上下文菜单,具体取决于您单击时选择的内容:

  • applicationObject.CommandBars["Tables"]
  • applicationObject.CommandBars["表格文本"]
  • applicationObject.CommandBars["表格单元格"]
  • applicationObject.CommandBars["表格标题"]
  • applicationObject.CommandBars["表列表"]
  • applicationObject.CommandBars["表格图片"]

因此,我建议您提取一个将按钮添加到CommandBar 的方法,然后使用您要添加按钮的所有命令栏调用该方法。类似于以下内容:

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"]);

【讨论】:

    【解决方案2】:

    好的,我终于成功修复了。

    首先,RightClick 有 200 多个不同的上下文菜单

    但是 word.application.CommandBars 的常见类型是基于索引下的 {105、120、127、117、108、99、134}; 这些是包含文本、表格、标题、文本框和...的索引。

    因此,您必须通过 foreach 更新您的代码以迭代创建新的 commandBarButtons 在每种类型的 ContextMenu 上 类似代码下的东西在你的启动功能上使用它

                    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);
                    }
    

    最后,

    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;
        }
    
    }
    

    希望对大家有帮助。 ;->

    【讨论】:

    • 天啊。谢谢你。我会试试的
    • 好的,让我知道结果
    【解决方案3】:

    正如 Dirk 所指出的,您需要单击原始问题下的 EDIT 链接,将信息粘贴到其末尾的“答案”中,然后删除“答案” - 这不是答案...

    我的答案基于您提供的其他信息。这显然是一个 VSTO 应用程序级插件。因此,对于 Office 2013,您需要使用功能区 XML 创建自定义菜单。功能区设计器无法做到这一点,因此如果您已有功能区设计器,则需要将其转换为功能区 XML。您可以在 VSTO 文档中找到有关如何执行此操作的文章: https://msdn.microsoft.com/en-us/library/aa942866.aspx

    有关如何使用 Ribbon XML 自定义上下文菜单的信息可以在这篇 MSDN 文章中找到: https://msdn.microsoft.com/en-us/library/ee691832(v=office.14)

    总结一下:您需要将 元素添加到功能区 XML 中,并为要添加或更改的每个菜单项添加一个 元素。元素的 idMso 属性指定 WHICH 上下文菜单。您可以在 Microsoft 网站的下载中找到 ControlId(idMso 的值)列表: https://www.microsoft.com/en-us/download/details.aspx?id=36798

    FWIW 该上下文菜单的 ControlId 可能是 ContextMenuTextTable。

    【讨论】:

    • 对不起,我还没做,帮帮我。使用功能区,当我右键单击 ms 单词表时,我仍然无法添加项目菜单
    • 单击原始问题下的“编辑”链接,并在其末尾粘贴您已添加到项目中的功能区 XML。此外,请非常确定您尝试右键单击的表格单元格包含什么样的内容。 Word 可以区分很多东西——例如是否标记了拼写错误——并且有一个单独的右键菜单来显示所有可能性。您可能需要将控件添加到多个上下文菜单中,以便在所有情况下都显示...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多