Title: How to start a program and wait for its termination (2)
// First create the special unit and put this code into this new unit:
uses
Windows, Registry, Dialogs, Classes, SysUtils;
var
aProcessInfo: PROCESS_INFORMATION;
aProcessSecAttr: SECURITY_ATTRIBUTES;
aThreadSecAttr: SECURITY_ATTRIBUTES;
aStartupInfo: STARTUPINFO;
function RunApp(commandLine: String): integer;
var
n: Boolean;
begin
with aProcessSecAttr do
begin
bInheritHandle := False;
lpSecurityDescriptor := nil;
nLength := sizeOf(aProcessSecAttr);
end;
with aThreadSecAttr do
begin
bInheritHandle := False;
lpSecurityDescriptor := nil;
nLength := sizeOf(aThreadSecAttr);
end;
with aStartupInfo do
begin
cb := sizeOf(aStartupInfo);
lpReserved := nil;
lpDesktop := nil;
lpTitle := nil;
dwX := 0;
dwY := 0;
dwXSize := 300;
dwYSize := 300;
dwXCountChars := 80;
dwYCountChars := 25;
dwFillAttribute := 0;
dwFlags := STARTF_USESTDHANDLES;
wShowWindow := SW_SHOWDEFAULT;
cbReserved2 := 0;
lpReserved2 := nil;
hStdInput := 0;
hStdError := 0;
hStdOutput := 0;
end;
n := CreateProcess(nil, @commandLine[1], nil, nil,
True, CREATE_NO_WINDOW + NORMAL_PRIORITY_CLASS,
nil, nil, aStartupInfo, aProcessInfo);
If n Then
RunApp := aProcessInfo.hProcess
Else
RunApp := -1;
end;
procedure CloseProcessHandles;
begin
CloseHandle(aProcessInfo.hThread);
CloseHandle(aProcessInfo.hProcess);
end;
// Then you may call the RunApp function:
hProcessHandle := RunApp(sPrintCmd);
if hProcessHandle 0 then
begin
WaitForSingleObject(hProcessHandle, _YOUR_WAIT_TIME_);
CloseProcessHandles;;
end;