无敌的Word CommandBar和它的Control们

本文介绍了如何在Word 2007中利用VBA和VSTO处理CommandBar和Ribbon,展示了如何添加自定义按钮,并通过CommandBar控制Ribbon的状态,以及解决在不同场景下利用CommandBar解决问题的例子。
摘要由CSDN通过智能技术生成

                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!");

            }

代码很简单,需要注意的地方是,buttonTag属性一定要赋值,还有添加button方法的最后一个参数设置为true,否则,当Word关闭的时候,添加的button将留在Word的工具栏上,下次打开Word会添加新的buttonbutton越来越多,这会让人想砸电脑。(可以通过删了Normal.dot把这些残留button删掉,当然还有其它方法)

以上的代码在Word 2003里跑,毫无疑问,工作正常。但是如果在只安装了Word 2007的机器上跑呢?Word 2007是没有MenuToolbar的,只有一个叫Ribbon的东西,Ribbon里面又有很多的TabTab里面再分GroupGroup

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值