MS Word插件:右键处理程序

4

我正在开发一个MS Word 2010的插件,希望在右键菜单中添加一些菜单项(仅当选择了一些文本时)。我看到了一些添加菜单项的例子,但找不到如何有条件地添加菜单项。 简而言之,我想覆盖类似OnRightClick处理程序的东西。 提前感谢。

1个回答

9
这很简单,你需要处理WindowBeforeRightClick事件。在事件内部,定位所需的命令栏和特定控件,并处理VisibleEnabled属性。
在下面的示例中,我基于所选内容(如果选择包含“C#”则隐藏该按钮,否则显示它)切换在文本命令栏上创建的自定义按钮的Visible属性。
    //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;
    }

1
这很容易,我想知道为什么我在搜索了这么多之后还是找不到这个处理程序 :) 不过还是谢谢。 - Mujtaba Hassan
将应用程序设置为this.Application会导致错误,因为在ThisAddIn_Startup期间它尚未打开。 - user8620003

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接