MS Word Add-in: RIght click handler

元气小坏坏 提交于 2019-12-21 05:35:22

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/11816358/ms-word-add-in-right-click-handler

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!