delphi中关于使用CreateOleObject方法控制word的一些心得,需要引用comobj单元。我只打开的函数,供大家分享。
打开word时,处理异常。使用GetActiveOleObject方法如果存在内存存在就直接调用,否则得创建;插入数据等操作……
procedure TfrmMain.N1Click(Sender: TObject);
var
h:THandle;
rec:trect;
isstyle :LongInt;
Fword,Fdoc,NewDoc:Variant;
Ffilename:string;
begin
try
try
Fword :=GetActiveOleObject('word.application');//判断内存中是否存在此程序
except
FWord :=CreateOleObject('word.Application');
end;
except
ShowMessage('创建失败!');
Exit;
end;
if od.Execute then
begin
try
NewDoc :=FWord.Documents.open(od.FileName) ;
except
MessageBox(Handle,'不支持此文件!','警告!',MB_ICONINFORMATION);
IsOpenWord :=False;
Exit;
end;
//FDoc :=FWord.documents.add; //新建文件
Ffilename :=od.FileName;
//FWord.ActiveDocument.Protect(2); //设置成保护类型,不可修改
FWord.application.CommandBars['Standard'].Visible:=false;
FWord.application.CommandBars['Formatting'].Visible := False;
FWord.application.CommandBars['Reviewing'].Visible:=false;
FWord.application.WindowState :='wdWindowStateNormal';
//-------插入内容
Fword.selection.TypeParagraph;//回车换行
Fword.Selection.typetext(Text :='[TextEdition][\TextEdition]');
Fword.selection.TypeParagraph;//回车换行
Fword.Selection.typetext(Text :='[Subject][\Subject]');
FWord.visible :=true;
//-------------放入Panel里面
sleep(700);
h:=findwindow('OpusApp',nil);//注意这里的窗口的类型
{
isstyle :=GetWindowLong(h, GWL_STYLE) ;
isstyle :=WS_MAXIMIZEBOX;
SetWindowLong(h,GWL_STYLE,isstyle) ; }
GetWindowRect(h,rec);
SetWindowPos(h,HWND_TOP,-1,-1,pnlCenter.Width,pnlCenter.Height,SWP_NOSIZE or SWP_SHOWWINDOW);
windows.SetParent(h,pnlCenter.Handle);
//-------------------------------
end;
end;
----------------------------------
Fword.ActiveDocument.undo;//撤销
Fword.ActiveDocument.redo; //重做
Fword.quit;//退出
Fword:= Unassigned;//退出