簡體   English   中英

如何在 Microsoft Office Word 中添加菜單項

[英]How to Add a Menu Item in Microsoft Office Word

我試圖根據這篇文章在 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 表格時,我無法添加項目菜單。 請幫我。 謝謝!!

對不起我的英語,...

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["表格"]
  • 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"]);

正如德克指出的那樣,您需要單擊原始問題下的編輯鏈接,將信息粘貼到“答案”末尾,然后刪除“答案”——這不是答案......

我的回答基於您提供的附加信息。 這顯然是一個 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)

總而言之:您需要向 Ribbon XML 添加一個 <contextMenus> 元素,並為每個要添加或更改的菜單項添加一個 <contextMenu> 元素。 元素的 idMso 屬性指定了哪個上下文菜單。 您可以在 Microsoft 站點的下載中找到 ControlIds(idMso 的值)列表: https : //www.microsoft.com/en-us/download/details.aspx? id=36798

FWIW 該上下文菜單的 ControlId 可能是 ContextMenuTextTable。

好的,最后我已經成功修復了它。

首先,RightClick 有 200 多個不同的上下文菜單

但是 word.application.CommandBars 的常見類型基於下索引 { 105, 120, 127, 117, 108, 99, 134 }; 這些包含文本、表格、標題、文本框和...的索引。

因此,您必須通過 foreach 更新您的代碼,以在每種類型的 ContextMenu 上迭代創建新的 commandBarButtons,就像在代碼下一樣在您的啟動函數上使用它

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

}

我希望它可以幫助你們。 ;->

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM