编程教程
您现在的位置: 中国个人站长站 >> 网络编程 >> Delphi >> 教程正文 在Delphi中捕获控制台程序的输出
推荐位

在Delphi中捕获控制台程序的输出

中国个人站长站 Delphi 点击数: 更新时间:2005-8-28 11:18:41

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

教程录入:swh    责任编辑:swh 
个人站长站与你风雨同舟!
本站所提供的资源均来源于互联网,如有侵权行为,请与本站管理员联系,我们会第一时间删除!
·如果您发现《在Delphi中捕获控制台程序的输出》文章有错误,也请通知我们修改!
联系邮箱chinageren#126.com,谢谢支持!
站内搜索:
广告服务 | 友情链接 | 联系我们 | 免责声明 | 用户留言 | 网站导航
版权所有:中国个人站长站 2007-2008 未经授权禁止复制或建立镜像 客服QQ号:112731235
copyright © 2007-2008 www.ChinaGeRen.com online services. all rights reserved. 苏ICP备05000059号