1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| procedure TForm1.GetConsoleText(const szCommande: String; var szResult: String);
const
LENBUFF = 512;
var
hReadPipe, hWritePipe: THandle;
sa: TSecurityAttributes;
si: TStartupInfo;
pi: TProcessInformation;
lpBuffer: Array[0..LENBUFF] of char;
nBytesRead: Cardinal;
nBytesToRead: Integer;
begin
sa.nLength := Sizeof(sa);
sa.lpSecurityDescriptor := nil;
sa.bInheritHandle := True;
if not CreatePipe(hReadPipe, hWritePipe, @sa, 0) then
begin
Application.MessageBox(PChar('Erreur : la création du pipe a échoué !' + #13#10 + SysErrorMessage(GetLastError)), PChar(Caption + ' - erreur'), MB_ICONERROR + MB_OK);
Exit;
end;
FillChar(si, Sizeof(si), 0);
si.cb := Sizeof(si);
si.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
si.wShowWindow := SW_HIDE;
si.hStdInput := 0;
si.hStdOutput := hWritePipe;
si.hStdError := hWritePipe;
if not CreateProcess(nil, PChar(szCommande), nil, nil, True, 0, nil, nil, si, pi) then
begin
Application.MessageBox(PChar('Erreur : l''exécution de la commande a échoué !' + #13#10 + SysErrorMessage(GetLastError)), PChar(Caption + ' - erreur'), MB_ICONERROR + MB_OK);
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
Exit;
end;
CloseHandle(hWritePipe);
nBytesToRead := LENBUFF;
nBytesRead := 0;
szResult := '';
while(True) do
begin
lpBuffer := '';
ReadFile(hReadPipe, lpBuffer, nBytesToRead, nBytesRead, nil);
if nBytesRead = 0 then
Break;
szResult := szResult + StrPas(lpBuffer);
end;
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(hReadPipe); |
Partager