Получаем вывод командной строки и консольных приложений. Вывод можно получить как после завершения запущенного приложения, так и в реальном времени, во время выполнения продолжительных операций.
1 2 3 4 5 6 7 |
var cmdline, output: WideString; begin cmdline:= 'ping 8.8.8.8'; output:= getCMDoutput(cmdline); ShowMessage(output); end; |
Параметры
cmdline - команда командной строки или путь к консольному приложению с параметрами
Результат
Текст возвращаемый командной строкой или приложением.
Для получения результата в реальном времени, укажите куда выводить текст, как в примере в строках 54-57.
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 66 67 68 69 70 |
function getCMDoutput(const cmdLine:WideString): WideString; var SA: TSecurityAttributes; SI: TStartupInfoA; PI: TProcessInformation; StdOutPipeRead, StdOutPipeWrite: THandle; WasOK: Boolean; Buffer: array[0..255] of AnsiChar; BytesRead: Cardinal; WorkDir, line: WideString; i:Integer; outStr: PWideChar; tmp:WideString; function StrOemToAnsi(const S: AnsiString): AnsiString; begin SetLength(Result, Length(S)); OemToAnsiBuff(@S[1], @Result[1], Length(S)); end; begin tmp:= Trim(cmdLine); tmp:= 'cmd /c ' + tmp; with SA do begin nLength := SizeOf(SA); bInheritHandle := True; lpSecurityDescriptor := nil; end; CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0); try with SI do begin FillChar(SI, SizeOf(SI), 0); cb := SizeOf(SI); dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; wShowWindow := SW_HIDE; hStdInput := GetStdHandle(STD_INPUT_HANDLE); hStdOutput := StdOutPipeWrite; hStdError := StdOutPipeWrite; end; WasOK:= CreateProcessa(nil, PAnsiChar(AnsiString(tmp)), nil, nil, True, 0, nil, nil, SI, PI); CloseHandle(StdOutPipeWrite); WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil); if BytesRead > 0 then begin Buffer[BytesRead] := #0; Line := Line + StrOemToAnsi(Buffer); // -----------------------------------------Вывод в Memo в реальном времени // Form1.Memo1.Lines.BeginUpdate; // Form1.Memo1.Text:= line; // Form1.Memo1.Lines.EndUpdate; // Application.ProcessMessages; //------------------------------------------------------------------------- end; until not WasOK or (BytesRead = 0); WaitForSingleObject(PI.hProcess, INFINITE); Result:= Line; finally CloseHandle(PI.hThread); CloseHandle(PI.hProcess); end; finally CloseHandle(StdOutPipeRead); end; end; |