We get the output of the command line and console applications. The output can be obtained both after the termination of the running application, and in real time, during the execution of long-term operations.
1 2 3 4 5 6 7 |
var cmdline, output: WideString; begin cmdline:= 'ping 8.8.8.8'; output:= getCMDoutput(cmdline); ShowMessage(output); end; |
Options
cmdline - command line command or path to console application with parameters
Result
The text returned by the command line or application.
To get the result in real time, specify where to output the text, as in the example on lines 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); // -----------------------------------------Output to Memo in real time // 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; |