Delphi:捕获控制台程序的输出
来源:优易学  2011-10-20 9:52:34   【优易学:中国教育考试门户网】   资料下载   IT书店

  本文实现了在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;

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训