function RunCaptured(
const _dirName, _exeName, _cmdLine:
string; AExitCode: boolean = False):
string;
var
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
Buffer:
array[0..255]
of char;
bRead: DWord;
hRead, hWrite: THandle;
saAttr: TSECURITYATTRIBUTES;
Output: TMemoryStream;
exitcode: cardinal;
begin
Result := '
';
saAttr.nLength := sizeof(TSECURITYATTRIBUTES);
saAttr.bInheritHandle := true;
saAttr.lpSecurityDescriptor :=
nil;
if not CreatePipe(hRead, hWrite, @saAttr, 0)
then
begin
ShowMessage('
Could not create Pipe!');
Result := '
ERROR: Could not create Pipe!';
Exit;
end;
try
FillChar(StartupInfo, Sizeof(StartupInfo), #0);
StartupInfo.cb := Sizeof(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW
or STARTF_USESTDHANDLES;
StartupInfo.wShowWindow := SW_HIDE
and SW_SHOWMINNOACTIVE;
{ Handle mit Childhandle Assoziieren }
StartupInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE);
{ Ausgaben abfangen }
StartupInfo.hStdOutput := hWrite;
{ Fehler abfangen }
StartupInfo.hStdError := hWrite;
if not CreateProcess(
nil, PChar(_exeName + '
' + _cmdLine),
nil,
nil, True,
0,
nil, PChar(_dirName), StartupInfo, ProcessInfo)
then
begin
ShowMessage('
Could not create process!');
Result := '
ERROR: Could not create process!';
end
else
begin
{ loop bis zum Abbruch }
while WaitforSingleObject(ProcessInfo.hProcess, 0) <> WAIT_OBJECT_0
do
{ dummy }
;
GetExitCodeProcess(ProcessInfo.hProcess, exitcode);
if AExitCode = False
then
begin
{ Den gesamten Output lesen und in eine StringList kopieren }
Output := TMemoryStream.Create;
Output.Clear;
repeat
Buffer := #0;
if ReadFile(hRead, Buffer, 80, bRead,
nil)
then
begin
Output.WriteBuffer(Buffer, bRead);
Output.Position := bRead;
end
else
break;
until bRead <> 80;
Output.Position := 0;
Buffer := #0;
{ Die Ausgaben hinzufügen }
{ Add the output }
output.
Read(Buffer, output.Size);
Result := Buffer;
FreeAndNil(Output);
end
else
Result := IntToStr(exitcode);
end;
finally
{ Lese- und Schreibhandles der Pipe schliessen }
CloseHandle(hRead);
CloseHandle(hWrite);
end;
end;