Word 2007在外观上和Word 2003比,改动很大。一个叫Ribbon的控件容器取代了过去Office版本中的菜单和工具栏。在Word 2003中,我们可以使用VBA, VSTO, Office Automation等等各种各样的技术,在菜单或者工具栏上添加自定义的按钮,实现我们想要的功能。C#版本的Automation代码,大致如下:
//Initial and show Word Application
Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
wordApp.Visible = true;
//Create a Command Bar
Office.CommandBar commandBar = wordApp.CommandBars.Add("My Bar",
Office.MsoBarPosition.msoBarTop, false, true);
commandBar.Visible = true;
//Add a Command Bar button
Office.CommandBarButton btn = commandBar.Controls.Add(Office.MsoControlType.msoControlButton,
missing, missing, missing, true) as Office.CommandBarButton;
btn.Caption = "My Button";
btn.Tag = "MyButton";
btn.Style = MsoButtonStyle.msoButtonCaption;
btn.Click += new _CommandBarButtonEvents_ClickEventHandler(btn_Click);
void btn_Click(CommandBarButton Ctrl, ref bool CancelDefault)
{
MessageBox.Show("My button is clicked!");
}
代码很简单,需要注意的地方是,button的Tag属性一定要赋值,还有添加button方法的最后一个参数设置为true,否则,当Word关闭的时候,添加的button将留在Word的工具栏上,下次打开Word会添加新的button,button越来越多,这会让人想砸电脑。(可以通过删了Normal.dot把这些残留button删掉,当然还有其它方法)
以上的代码在Word 2003里跑,毫无疑问,工作正常。但是如果在只安装了Word 2007的机器上跑呢?Word 2007是没有Menu和Toolbar的,只有一个叫Ribbon的东西,Ribbon里面又有很多的Tab,Tab里面再分Group,Group