Capture the output of the console program in Delphi

zhaozj2021-02-08  445

This article implements run the console program in Delphi, and the output of the console program is displayed in the MEMO control.

Work is required to manually compile J2ME, start writing a batch program, but it feels very cumbersome in use, so I want to use Delphi to make an integrated compilation tool, but Java's compilation tool is console program, how to capture the console program Output, and displayed in MEMO, check some information on the Internet, repeated test, find a realization method, I hope to help everyone:

procedure TMainForm.RunDosInMemo (const DosApp: string; AMemo: TMemo); const {set the size of ReadBuffer} ReadBuffer = 2400; var Security: TSecurityAttributes; ReadPipe, WritePipe: THandle; start: TStartUpInfo; ProcessInfo: TProcessInformation; Buffer: PChar; BytesRead : DWord; Buf: string; begin with Security do begin nlength: = SizeOf (TSecurityAttributes); binherithandle: = true; lpsecuritydescriptor: = nil; end; {create a named pipe used to capture the program output console} if createpipe (ReadPipe, Writepipe, @security, 0) The begin buffer: = allocmem (readbuffer 1); FillChar (start, sizeof (start), # 0) {Set the starting attribute of the console program} with start do beg cb: = Sizeof (start) Start.lpreserved: = nil; lpdesktop: = nil; lpTitle: = nil; dwx: = 0; dwy: = 0; dwxsize: = 0; dwysize: = 0; dwxcountchars: = 0; dwycountchars: = 0; dwfillattribute: = 0; CBRESERVED2: = 0; lpreserved2: = nil; hstdoutput: = writepipe; // Output orientate to We create HSTDINPUT : = ReadPipe; // input directed to the ReadPipe hStdError we created: = WritePipe; // error output will be directed to the WritePipe we have established dwFlags: = STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; wShowWindow: = SW_HIDE; // set the window to hide END;

try {create a child process to run console program} if CreateProcess (nil, PChar (DosApp), @Security, @Security, true, NORMAL_PRIORITY_CLASS, nil, nil, start, ProcessInfo) then begin {wait for the process to run end} WaitForSingleObject (ProcessInfo .hprocess, infinite); {Close Output ... The start did not turn off it, the result If there is no output, the program is dead. } CloseHandle (WritePipe); BUF: = ''; {Output of the Console program} Repeat BytesRead: = 0; ReadFile (Readpipe, Buffer [0], Readput, BytesRead, nil); buffer [bytesRead]: = # 0 OEMTOANSI (Buffer, Buffer); BUF: = BUF String (buffer); Until (BytesRead 0 Do Begin AMemo.lines.add (BUF, 1, POS (# 10, buf) - 1))); delete (buf, 1, pOS (# 10, buf)); end; end; finally FreeMem (buffer); CloseHandle (ProcessInfo.hprocess); CloseHandle (ProcessInfo.hthread); CloseHandle (READPIPE); End; end;

转载请注明原文地址:https://www.9cbs.com/read-935.html

New Post(0)