加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Delphi 6 – 运行时读取控制台应用程序的输出

发布时间:2020-12-15 04:29:42 所属栏目:大数据 来源:网络整理
导读:在运行控制台应用程序输出时,如何读取它.我启动控制台应用程序,并希望读取由控制台应用程序打印的输出. 解决方法 这个 solution怎么样 编辑:链接导致了这个解决方案(轻轻地重构了可读性和删除使用): // The example runs 'chkdsk.exe c:' and displays th
在运行控制台应用程序输出时,如何读取它.我启动控制台应用程序,并希望读取由控制台应用程序打印的输出.

解决方法

这个 solution怎么样

编辑:链接导致了这个解决方案(轻轻地重构了可读性和删除使用):

// The example runs 'chkdsk.exe c:' and displays the output to Memo1.
// Put a TMemo (Memo1) and a TButton (Button1) on your form. Put this 
//   code in the OnCLick event procedure for Button1:

procedure TForm1.RunDosInMemo(DosApp:String;AMemo:TMemo) ;
const
  ReadBuffer = 2400;
var
  Security    : TSecurityAttributes;
  ReadPipe,WritePipe   : THandle;
  start       : TStartUpInfo;
  ProcessInfo : TProcessInformation;
  Buffer      : Pchar;
  BytesRead   : DWord;
  Apprunning  : DWord;

begin
  Security.nlength := SizeOf(TSecurityAttributes) ;
  Security.binherithandle := true;
  Security.lpsecuritydescriptor := nil;
  if Createpipe (ReadPipe,WritePipe,@Security,0) then 
  begin
    Buffer := AllocMem(ReadBuffer + 1) ;
    FillChar(Start,Sizeof(Start),#0) ;
    start.cb := SizeOf(start) ;
    start.hStdOutput := WritePipe;
    start.hStdInput := ReadPipe;
    start.dwFlags := STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW;
    start.wShowWindow := SW_HIDE;
    if CreateProcess(nil,PChar(DosApp),true,NORMAL_PRIORITY_CLASS,nil,start,ProcessInfo) then
    begin
      repeat
        Apprunning := WaitForSingleObject(ProcessInfo.hProcess,100);
        Application.ProcessMessages;
      until (Apprunning <> WAIT_TIMEOUT) ;
      repeat
        BytesRead := 0;
        ReadFile(ReadPipe,Buffer[0],ReadBuffer,BytesRead,nil) ;
        Buffer[BytesRead]:= #0;
        OemToAnsi(Buffer,Buffer) ;
        AMemo.Text := AMemo.text + String(Buffer) ;
      until (BytesRead < ReadBuffer) ;
    end;
    FreeMem(Buffer) ;
    CloseHandle(ProcessInfo.hProcess) ;
    CloseHandle(ProcessInfo.hThread) ;
    CloseHandle(ReadPipe) ;
    CloseHandle(WritePipe) ;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject) ;
begin
  RunDosInMemo('chkdsk.exe c:',Memo1) ;
end;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读