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 56 57 58 59 60 61 62 63 64 65
| procedure ExecuteCommand(const CommandLine: String; out OutputMsg: String; out ExitCode: DWORD);
var
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
SecurityAttr: TSecurityAttributes;
hRead, hWrite: THandle;
Buffer: array[0..255] of AnsiChar;
BytesRead: DWORD;
Cmd: string;
begin
OutputMsg := '';
SecurityAttr.nLength := SizeOf(TSecurityAttributes);
SecurityAttr.bInheritHandle := True;
SecurityAttr.lpSecurityDescriptor := nil;
if not CreatePipe(hRead, hWrite, @SecurityAttr, 0) then
raise Exception.Create('Impossible de créer le pipe.');
try
ZeroMemory(@StartupInfo, SizeOf(StartupInfo));
StartupInfo.cb := SizeOf(StartupInfo);
StartupInfo.hStdOutput := hWrite;
StartupInfo.hStdError := hWrite;
StartupInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow:= SW_HIDE;
Cmd := 'cmd.exe /c ' + CommandLine;
if not CreateProcess(nil, PChar(Cmd), nil, nil, True,
CREATE_NO_WINDOW, nil, nil, StartupInfo, ProcessInfo) then
raise Exception.Create('Erreur lors de la création du processus.');
try
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
if not GetExitCodeProcess(ProcessInfo.hProcess, ExitCode) then
raise Exception.Create('Impossible de récupérer le code de retour.');
CloseHandle(hWrite);
hWrite := 0;
repeat
if ReadFile(hRead, Buffer, SizeOf(Buffer) - 1, BytesRead, nil) then
begin
Buffer[BytesRead] := #0;
OutputMsg := OutputMsg + string(Buffer);
end;
until BytesRead < (SizeOf(Buffer) - 1);
finally
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
end;
finally
if hRead <> 0 then CloseHandle(hRead);
if hWrite <> 0 then CloseHandle(hWrite);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Msg: String;
Code: DWORD;
begin
ExecuteCommand('java -version', Msg, Code);
ShowMessage('Message : ' + Msg + sLineBreak + 'Code de retour : ' + IntToStr(Code));
end; |
Partager