Title: Monitoring an application (in an own thread)
Question: I need to run another application and then monitor it, waiting for it to close. My program needs to do other things while this is happening to it'd be helpful if this was multithreaded.
Answer:
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
const unitName = 'runThread_.';
type TRunThread = class(TThread)
private
processHandle : cardinal;
processReady : boolean;
waitingThread : cardinal;
procedure Execute; override;
end;
procedure TRunThread.Execute;
begin
WaitForSingleObject(processHandle,INFINITE);
processReady:=true;
PostThreadMessage(waitingThread,WM_NULL,0,0);
end;
procedure TForm1.Button1Click(Sender: TObject);
var si : TStartupInfo;
pi : TProcessInformation;
dw1 : dword;
begin
enabled:=false;
caption:='start copy...';
ZeroMemory(@si,sizeOf(si)); si.cb:=sizeOf(si);
si.dwFlags:=STARTF_USESHOWWINDOW; si.wShowWindow:=SW_NORMAL;
if CreateProcess(nil,'c:\windows\notepad.exe', nil, nil, false, 0,
nil, nil, si, pi) then
begin
caption:='copy started...';
with TRunThread.Create(true) do
try
processHandle:=pi.hProcess;
processReady:=false;
waitingThread:=GetCurrentThreadID;
caption:='notepad...';
Resume;
repeat
Application.HandleMessage;
until Application.Terminated or processReady;
caption:='notepad closed...';
finally Free end;
GetExitCodeProcess(pi.hProcess,dw1);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
caption:='ready... (exitCode='+IntToStr(dw1)+')';
end else caption:='could not start notepad...';
enabled:=true;
end;
end.