| 首页 | 电脑常识 | 程序设计 | 操作系统 | 语法 | 病毒安全 | 软件教程 | 硬件 | 数据库 | 多媒体 | 认证 | 下载 | 
首页>>程序设计 >>系统
执行控制台程序并且获得它的输出结果

执行控制台程序并且获得它的输出结果

电脑学习网,xuef.com,最全最新最权威的电脑知识网站.
免费计算机学习教程,电脑入门指南.
前几日遇到的问题在各位的帮助下已经圆满解决,现在吧这段代码写出来,可能会有一点用处。
procedure CheckResult(b: Boolean);
begin
  if not b then
    Raise Exception.Create(SysErrorMessage(GetLastError));
end;

function RunDOS(const Prog, CommandLine,Dir: String;var ExitCode:DWORD): String;
var
  HRead,HWrite:THandle;
  StartInfo:TStartupInfo;
  ProceInfo:TProcessInformation;
  b:Boolean;
  sa:TSecurityAttributes;
  inS:THandleStream;
  sRet:TStrings;
begin
  Result := ';
  FillChar(sa,sizeof(sa),0);
  //设置允许继承,否则在NT和2000下无法取得输出结果
  sa.nLength := sizeof(sa);
  sa.bInheritHandle := True;
  sa.lpSecurityDescriptor := nil;
  b := CreatePipe(HRead,HWrite,@sa,0);
  CheckResult(b);

  FillChar(StartInfo,SizeOf(StartInfo),0);
  StartInfo.cb := SizeOf(StartInfo);
  StartInfo.wShowWindow := SW_HIDE;
  //使用指定的句柄作为标准输入输出的文件句柄,使用指定的显示方式
  StartInfo.dwFlags    := STARTF_USESTDHANDLES+STARTF_USESHOWWINDOW;
  StartInfo.hStdError  := HWrite;
  StartInfo.hStdInput  := GetStdHandle(STD_INPUT_HANDLE);//HRead;
  StartInfo.hStdOutput  := HWrite;

  b := CreateProcess(PChar(Prog),//lpApplicationName: PChar     
        PChar(CommandLine),    //lpCommandLine: PChar
        nil,    //lpProcessAttributes: PSecurityAttributes
        nil,    //lpThreadAttributes: PSecurityAttributes
        True,    //bInheritHandles: BOOL
        CREATE_NEW_CONSOLE,
        nil,       
        PChar(Dir),
        StartInfo,
        ProceInfo    );

  CheckResult(b);
  WaitForSingleObject(ProceInfo.hProcess,INFINITE);
  GetExitCodeProcess(ProceInfo.hProcess,ExitCode);

  inS := THandleStream.Create(HRead);
  if inS.Size>0 then
  begin
    sRet := TStringList.Create;
    sRet.LoadFromStream(inS);
    Result := sRet.Text;
    sRet.Free;
  end;
  inS.Free;

  CloseHandle(HRead);
  CloseHandle(HWrite);
end;
相 关 文 章
  • 把数据集保存为Excel格式的一个实现

  • 用Delphi开发报表打印的ASP组件

  • 用Delphi制作中国式报表

  • Delphi与Excel的亲密接触

  • delphi中使用ReportMachine解决中式带边条及固定行的疑难报表(上)

  • 如何用Tprinter设计BCB操作数据库程序中的报表

  • 利用剪贴板实现高速导出数据到Excel

  • 在Delphi中自己建立交叉表

  • 应用程序敏感键的实现

  • 在DELPHI中用线程排序

  • 学府网电脑学习的乐园
    中国电脑教学网,电脑爱好者的乐园,做最好最全的计算机学习网站.