TWordApplication是Delphi 5中带的Server组件,ConnectTo 方法是用来连接插件和Word提供的接口。因为TWordApplication 把接口事件映射成了Delphi事件,
我们可以直接使用标准的Delphi语法来设定事件处理过程。示意如下:
WordApp.OnEventX := EventXHandler;
比如
我们如果想在Word的选区发生改变时实现某项功能,就可以设定OnWindowSelectionChange 事件。
插件如何创建新的工具条、按钮和菜单
在创建新的工具条和按钮前,需要为按钮的OnClick过程先创建事件处理函数,下面就是简单的处理函数例子:
procedure TAddIn.TestClick(const Ctrl: OleVariant;
var CancelDefault: OleVariant);
begin
ShowMessage(有人点
我了!);
CancelDefault := True;
end;
CancelDefault参数用来设定是否替代缺省的菜单或工具条按钮的处理过程。这里不需要设定这个参数,因为
我们将在插件中创建一个新的按钮。插件注册为在程序启动时被加载,所以OnStartupComplete方法一定会被调用,用这个方法创建用户界面元素是比较合适的。这里定义BtnIntf为CommandBarControl接口类型(要创建的CommandBarButton的父类接口)。接下来的任务是确定自定义的工具条是否已经被创建了
DICommandBar := nil;
for i := 1 to WordApp.CommandBars.Count do
if (WordApp.CommandBars.Item[i].Name =Delphi) then
DICommandBar := WordApp.CommandBars.Item[i];
// 确定是否已经注册了命令条
if (not Assigned(DICommandBar)) then begin
DICommandBar:=
WordApp.CommandBars.Add(Delphi,EmptyParam,EmptyParam,EmptyParam);
DICommandBar.Set_Protection(msoBarNoCustomize)
end;
先给工具条起一个唯一的名字“Delphi”,然后在启动时检查工具条是否已经被创建了。如果是的话就把它赋值给DICommandBar,否则调用Word的CommandBars属性的Add方法创建一个新的工具条。接着给工具条添加msoBarNoCustomize的保护,这可以防止用户添加或删除工具条上的按钮。这时DICommandBar指向一个有效的工具条,
我们可以从接口的Controls集合中获得工具条按钮接口指针。如果工具条上没有控件,就创建一个新的按钮。
if (DICommandBar.Controls.Count > 0) then
BtnIntf := DICommandBar.Controls.Item[1]
else
BtnIntf := DICommandBar.Controls.Add(msoControlButton,
EmptyParam, EmptyParam, EmptyParam, EmptyParam);
注意:集合中第一项是以1为底的,而不像Delphi中那样通常以0为底。现在
我们获得了需要的工具条按钮接口,然后要创建一个基于按钮接口的TButtonServer 类封装。
DIBtn := TButtonServer.Create(nil);
DIBtn.ConnectTo(BtnIntf as _CommandBarButton);
DIBtn.Caption := Delphi Test;
DIBtn.Style := msoButtonCaption;
DIBtn.Visible := True;
DIBtn.OnClick := TestClick;
这里使用ConnectTo 方法连接按钮的事件并设定先前创建的OnClick事件处理过程。最后,要确认使工具条可见。
DICommandBar.Set_Visible(True);
TLIBIMP程序创建了一个只读的而非可读写的工具条Visible 属性,但可以使用Set_Visible 方法来设定显示属性(不能生成可读写的属性可能是TLIBIMP的bug)。添加新的菜单项类似于前面,首先创建菜单的OnClick事件处理函数,下面这个过程遍历被选文本的第一段,并设定其边框样式:
procedure TAddIn.MenuClick(const Ctrl: OleVariant;
var CancelDefault: OleVariant);
var
Sel : Word_TLB.Selection;
Par : Word_TLB.Paragraph;
begin
Sel := WordApp.ActiveWindow.Selection;
if (Sel.Type_ in [wdSelectionNormal,
wdSelectionIP]) then begin
Par := Sel.Paragraphs.Item(1);
if (Par.Borders.OutsideLineStyle < wdLineStyleInset) then
Par.Borders.OutsideLineStyle := 1 + Par.Borders.OutsideLineStyle
else
Par.Borders.OutsideLineStyle := wdLineStyleNone;
end;
end;