2012-08-05 77 views
4

我正在开发用于MS Word 2010的加载项,我想将几​​个菜单项添加到右键单击菜单(仅在选择某些文本时)。我看过几个例子来添加项目,但无法找到如何有条件地添加项目。 总之我想重写像OnRightClick处理程序。 在此先感谢。MS Word加载项:右键单击处理程序

回答

9

这很简单,你需要处理WindowBeforeRightClick事件。在活动内部找到所需的命令栏和特定控件,并处理VisibleEnabled属性。

在下面我切换文本命令栏上创建自定义按钮的Visible财产基础上的选择(如果选择包含“C#”隐藏按钮,否则显示它)的例子

//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

这很容易,我想知道如何在google搜索之后找不到这个处理程序:)谢谢 – 2012-10-31 10:00:20