在Delphi中捕獲控制檯程式的輸出 (轉)

worldblog發表於2007-12-13
在Delphi中捕獲控制檯程式的輸出 (轉)[@more@]

本文實現了在中執行控制檯,並將控制檯程式的輸出在Memo中顯示出來。

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

procedure TMainForm.RunDosInMemo(const DosApp: string; AMemo: TMemo);
const
  {設定Reauffer的大小}
  ReadBuffer = 2400;
var
  Security: TSecurityAttributes;
  ReadPipe, WritePipe: THandle;
  start: TStartUpInfo;
  ProcessInfo: TProcessInformation;
  Buffer: PChar;
  BytesRead: D;
  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_H;//設定視窗為hide
  end;

  try
 {建立一個子程式,執行console程式}
  if CreateProcess(nil, PChar(DosApp), @Security, @Security, true,
  NORMAL_PRIORITY_CLASS,
  nil, nil, start, ProcessInfo) then
  begin
  {等待程式執行結束}
  WaitForSingle(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);

  SendDe(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;


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-992876/,如需轉載,請註明出處,否則將追究法律責任。

相關文章