Originally Posted by
rvk
Computer opnieuw opstarten.
Uiteindelijk is het in orde gekomen met mijn probleem: ik heb een paar retries ingebouwd. Ik zie dat soms 1 of 2 retries nodig zijn bij 'CreateOleObject' vooraleer het lukt.
Het doel van het programma was de inhoud van een word file (of .wps file) in te lezen en die inhoud via het clipboard binnen te halen. Ook bij gebruik van het clipboard heb ik een paar delays moeten inbouwen omdat anders soms het clipboard leeg bleek te zijn...
Hier de volledige code:
Code:
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Variants, ComObj, ClipBrd, Windows;
...
procedure TForm1.Button1Click(Sender: TObject);
const
ServerName: ansistring = 'Word.Application';
var
Server: olevariant;
w: WideString;
Item_, CharsCount: integer;
ClipBoard: TClipBoard;
Res: string;
Cnt: byte;
begin
Cnt := 0;
Label1.Caption := IntToStr(Cnt);
try
Server := CreateOleObject(ServerName);
except
try
inc(Cnt);
Label1.Caption := IntToStr(Cnt);
Sleep(300);
Server := CreateOleObject(ServerName);
except
try
inc(Cnt);
Label1.Caption := IntToStr(Cnt);
Sleep(300);
Server := CreateOleObject(ServerName);
except
inc(Cnt);
Label1.Caption := IntToStr(Cnt);
ShowMessage('Unable to start Word.');
Exit;
end;
end;
end;
{Open existing document}//Substitute your path and doc
w := 'C:\Lazarus Projects\First test\factuur 011.wps';
Server.Documents.Open(w);
//OLE uses BSTR (http://msdn.microsoft.com/en-us/library/windows/desktop/ms221069(v=vs.85).aspx). Only widestring is compatible with BSTR in FPC, so conversion is needed for nonlatin chars.
Server.Visible := False; {Make Word invisible}
Item_ := 1;
CharsCount := Server.Documents.item(Item_).Characters.Count;
//get the number of chars to select
Server.Selection.SetRange(0, CharsCount); //make the selection
ClipBoard := TClipboard.Create;
sleep(10);
Server.Selection.Copy; //copy to the clipboard
sleep(10);
Res := Clipboard.AsText; //get the text from the clipboard
Clipboard.Free;
Server.Quit;
Res := StringReplace(Res, #9, ' ', [rfReplaceAll]);
ShowMessage(Res);
end;
Idereen bedankt voor het meedenken!
Bookmarks