天天看點

将Word嵌入Delphi中

unit Main;

interface

uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, ExtCtrls, StdCtrls,Comobj;

type

  TForm1 = class(TForm)

    Panel1: TPanel;

    Panel2: TPanel;

    Label1: TLabel;

    Button1: TButton;

    Button2: TButton;

    Button3: TButton;

    procedure Panel1Resize(Sender: TObject);

    procedure Button2Click(Sender: TObject);

    procedure Button1Click(Sender: TObject);

  private

    { Private declarations }

    FComApp:OleVariant;

    gWaveHwnd:Hwnd;

  public

    { Public declarations }

    procedure SetParentWindow(pParent: TWinControl);

  end;

var

  Form1: TForm1;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);

  Word : Variant;

begin

  FComApp := CreateOLEObject('Word.Application');

  FComApp.Documents.Open(extractfilepath(Application.ExeName)+'\test.doc',false);

  FComApp.Visible := True;

  Label1.Caption := FComApp.ActiveWindow.Caption;

end;

procedure TForm1.Button2Click(Sender: TObject);

  SetParentWindow(Panel1);

procedure TForm1.Panel1Resize(Sender: TObject);

  if gWaveHwnd<>0 then

  begin

    FComApp.ActiveWindow.Height := Panel1.Height;

    FComApp.ActiveWindow.Width := Panel1.Width;

    Windows.MoveWindow(gWaveHwnd,0,0,Panel1.Width,Panel1.Height,false);

procedure TForm1.SetParentWindow(pParent: TWinControl);

  lWaveHwnd : Hwnd;

  lWidth, lHeight: Integer;

  lWindowCaption: String;

  //lwaveHwnd := FindWindow(nil,'Microsoft Word');//視窗标題

  lWindowCaption := FComApp.ActiveWindow.Caption;

  lwaveHwnd := FindWindow(nil,pAnsiChar(lWindowCaption+' - Microsoft Word'));//視窗标題

  //lwaveHwnd := FindWindowW(nil,pWideChar(String(FComApp.ActiveWindow.Caption)));//視窗标題

  Windows.SetWindowLong(lWaveHwnd,GWL_STYLE,GetWindowLong(lWaveHwnd, GWL_STYLE)

                         and not (WS_CAPTION or WS_SYSMENU));

  Windows.SetParent(lWaveHwnd,pParent.Handle);

  gWaveHwnd:=lWaveHwnd;

  lWidth := pParent.Width;

  lHeight := pParent.Height;

  Windows.MoveWindow(lWaveHwnd,0,0,lWidth,lHeight,false);

  //mParent := pParent;

end.

繼續閱讀