function Win32ExecAndWait(const CommandLine, Directory:
string; out OutputString: string): integer;
var
SA: TSecurityAttributes;
SI: TStartupInfo;
PI: TProcessInformation;
StdOutPipeRead, StdOutPipeWrite: THandle;
WasOK: Boolean;
Buffer: array[0..255] of AnsiChar;
PDirectory: PChar;
BytesRead: Cardinal;
begin
Result := -1;
OutputString := '';
if Directory = '' then
PDirectory := nil
else
PDirectory := PChar(Directory);
FillChar(SA, SizeOf(SA), 0);
FillChar(SI, SizeOf(SI), 0);
with SA do
begin
nLength := SizeOf(SA);
bInheritHandle := True;
lpSecurityDescriptor := nil;
end;
CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
try
with SI do
begin
cb := SizeOf(SI);
dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow := SW_HIDE;
hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
hStdOutput := StdOutPipeWrite;
hStdError := StdOutPipeWrite;
end;
if not CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine),
nil, nil, True, 0, nil, PDirectory, SI, PI) then
Result := -1
else
begin
CloseHandle(StdOutPipeWrite);
try
repeat
WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil);
if BytesRead > 0 then
begin
Buffer[BytesRead] := #0;
OutputString := OutputString + Buffer;
end;
until not WasOK or (BytesRead = 0);
WaitForSingleObject(PI.hProcess, INFINITE);
GetExitCodeProcess(PI.hProcess, Cardinal(Result));
finally
CloseHandle(PI.hThread);
CloseHandle(PI.hProcess);
end;
end;
finally
CloseHandle(StdOutPipeRead);
end;
end;
Posted via ActualForum NNTP Server 1.5