Delphi中捕獲控制檯程序的輸出

 本文實現了在Delphi中運行控制檯程序,並將控制檯程序的輸出在Memo控件中顯示出來。

工作中需要手工編譯J2ME的程序,開始編寫了一個批處理程序,但是感覺使用中非常繁瑣,於是想用Delphi做一個集成編譯工具,但是java的編譯工具都是console程序,怎麼捕獲到console程序的輸出,並顯示在Memo中呢,查了網上的一些資料,反覆測試,找到了一個實現的方法,希望對大家有幫助:

procedure TMainForm.RunDosInMemo(const DosApp: string; AMemo: TMemo);
const
  {設置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;
  {創建一個命名管道用來捕獲console程序的輸出}
  if Createpipe(ReadPipe, WritePipe, @Security, 0) then
  begin
    Buffer := AllocMem(ReadBuffer + 1);
    FillChar(Start, Sizeof(Start), #0)
    {設置console程序的啓動屬性}
    with start do
    begin
      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; //將輸出定向到我們建立的WritePipe上
      hStdInput := ReadPipe; //將輸入定向到我們建立的ReadPipe上
      hStdError := WritePipe;//將錯誤輸出定向到我們建立的WritePipe上
      dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
      wShowWindow := SW_HIDE;//設置窗口爲hide
    end;

    try
      {創建一個子進程,運行console程序}
      if CreateProcess(nil, PChar(DosApp), @Security, @Security, true,
        NORMAL_PRIORITY_CLASS,
        nil, nil, start, ProcessInfo) then
      begin
       {等待進程運行結束}
        WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
        {關閉輸出...開始沒有關掉它,結果如果沒有輸出的話,程序死掉了。}
        CloseHandle(WritePipe);
        Buf := ';
        {讀取console程序的輸出}
        repeat
          BytesRead := 0;
          ReadFile(ReadPipe, Buffer[0], ReadBuffer, BytesRead, nil);
          Buffer[BytesRead] := #0;
          OemToAnsi(Buffer, Buffer);
          Buf := Buf + string(Buffer);
        until (BytesRead < ReadBuffer);

        SendDebug(Buf);
       {按照換行符進行分割,並在Memo中顯示出來}
        while pos(#10, Buf) > 0 do
        begin
          AMemo.Lines.Add(Copy(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;
end;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章