我正在为MS Word 2010开发一个加载项,我想在右键菜单中添加几个菜单项(仅当选择了一些文本时).我看过几个例子来添加项目,但无法找到如何有条件地添加项目.简而言之,我想覆盖像OnRightClick处理程序之类的东西.提前致谢.
这很简单,你需要处理这个WindowBeforeRightClick事件.在事件内部找到所需的命令栏和specfic控件并处理Visible或Enabled属性.
在下面的示例中,我根据选择切换在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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3844 次 |
| 最近记录: |