procedure THauptForm.GetConsoleOutput(
const Command:
String);
var
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
SecurityAttr: TSecurityAttributes;
PipeOutputRead: THandle;
PipeOutputWrite: THandle;
PipeErrorsRead: THandle;
PipeErrorsWrite: THandle;
Succeed: Boolean;
Buffer:
array [0..255]
of Char;
NumberOfBytesRead: DWORD;
Stream: TMemoryStream;
begin
//Initialisierung ProcessInfo
FillChar(ProcessInfo, SizeOf(TProcessInformation), 0);
//Initialisierung SecurityAttr
FillChar(SecurityAttr, SizeOf(TSecurityAttributes), 0);
SecurityAttr.nLength := SizeOf(SecurityAttr);
SecurityAttr.bInheritHandle := true;
SecurityAttr.lpSecurityDescriptor :=
nil;
//Pipes erzeugen
CreatePipe(PipeOutputRead, PipeOutputWrite, @SecurityAttr, 0);
CreatePipe(PipeErrorsRead, PipeErrorsWrite, @SecurityAttr, 0);
//Initialisierung StartupInfo
FillChar(StartupInfo, SizeOf(TStartupInfo), 0);
StartupInfo.cb:=SizeOf(StartupInfo);
StartupInfo.hStdInput := 0;
StartupInfo.hStdOutput := PipeOutputWrite;
StartupInfo.hStdError := PipeErrorsWrite;
StartupInfo.wShowWindow := sw_Hide;
StartupInfo.dwFlags := STARTF_USESHOWWINDOW
or STARTF_USESTDHANDLES;
if CreateProcess(
nil, PChar(command),
nil,
nil, true,
CREATE_DEFAULT_ERROR_MODE
or CREATE_NEW_CONSOLE
or NORMAL_PRIORITY_CLASS,
nil,
nil,
StartupInfo, ProcessInfo)
then begin
//Write-Pipes schließen
CloseHandle(PipeOutputWrite);
CloseHandle(PipeErrorsWrite);
//Ausgabe Read-Pipe auslesen
Abbruch:=false;
MmAusgabe.Clear;
MmAusgabe.Lines.Add('
');
try
while true
do begin
succeed := ReadFile(PipeOutputRead, Buffer, 255, NumberOfBytesRead,
nil);
if not succeed
then break;
MmAusgabe.Lines[0]:=MmAusgabe.Lines[0] + Buffer;
Application.ProcessMessages;
if Abbruch
then exit;
end;
finally
Stream.Free;
end;
CloseHandle(PipeOutputRead);
//Fehler Read-Pipe auslesen
try
while true
do begin
succeed := ReadFile(PipeErrorsRead, Buffer, 255, NumberOfBytesRead,
nil);
if not succeed
then break;
MmAusgabe.Lines[0]:=MmAusgabe.Lines[0] + Buffer;
Application.ProcessMessages;
if Abbruch
then exit;
end;
finally
Stream.Free;
end;
CloseHandle(PipeErrorsRead);
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
CloseHandle(ProcessInfo.hProcess);
end
else begin
CloseHandle(PipeOutputRead);
CloseHandle(PipeOutputWrite);
CloseHandle(PipeErrorsRead);
CloseHandle(PipeErrorsWrite);
end;
end;
procedure THauptForm.BtTestClick(Sender: TObject);
begin
GetConsoleOutput('
cmd /c dir c:\winnt /s');
end;