Delphi 执行控制台(console)程序获取返回结果


本文整理自网络,侵删。

 
function GetRunConsoleResult(FileName:String;Visibility:Integer;var mOutputs:string):Integer;  
var  
  sa:TSecurityAttributes;  
  hReadPipe,hWritePipe:THandle;  
  ret:BOOL;  
  strBuff:array[0..255] of char;  
  lngBytesread:DWORD;  
    
  WorkDir:String;  
  StartupInfo:TStartupInfo;  
  ProcessInfo:TProcessInformation;  
begin  
  FillChar(sa,Sizeof(sa),#0);  
  sa.nLength := Sizeof(sa);  
  sa.bInheritHandle := True;  
  sa.lpSecurityDescriptor := nil;  
  if not(CreatePipe(hReadPipe, hWritePipe, @sa, 0)) then  
    begin  
      Result:=-2;  //通道创建失败  
    end;  
  WorkDir:=ExtractFileDir(Application.ExeName);  
  FillChar(StartupInfo,Sizeof(StartupInfo),#0);  
  StartupInfo.cb:=Sizeof(StartupInfo);  
  StartupInfo.dwFlags:=STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;  
  StartupInfo.wShowWindow:=Visibility;  
  
  StartupInfo.hStdOutput:=hWritePipe;  
  StartupInfo.hStdError:=hWritePipe;  
  
  if not CreateProcess(nil,  
    PChar(FileName),               { pointer to command line string }  
    @sa,                           { pointer to process security attributes }  
    @sa,                           { pointer to thread security attributes }  
    True,                          { handle inheritance flag }  
    NORMAL_PRIORITY_CLASS,  
    nil,                           { pointer to new environment block }  
    PChar(WorkDir),                { pointer to current directory name, PChar}  
    StartupInfo,                   { pointer to STARTUPINFO }  
    ProcessInfo)                   { pointer to PROCESS_INF }  
  then  
    Result := INFINITE {-1 进程创建失败}  
  else  
    begin  
      CloseHandle(hWritePipe);  
      mOutputs:='';  
      while ret do  
      begin  
        FillChar(strBuff,Sizeof(strBuff),#0);  
        ret := ReadFile(hReadPipe, strBuff, 256, lngBytesread, nil);  
        mOutputs := mOutputs + strBuff;  
      end;  
  
      Application.ProcessMessages;  
      //等待console结束  
      WaitforSingleObject(ProcessInfo.hProcess, INFINITE);  
      GetExitCodeProcess(ProcessInfo.hProcess,  Cardinal(Result));  
      CloseHandle(ProcessInfo.hProcess);  { to prevent memory leaks }  
      CloseHandle(ProcessInfo.hThread);  
      CloseHandle(hReadPipe);  
    end;  
end;  

调用方式:

 在CODE上查看代码片派生到我的代码片
GetRunConsoleResult(执行文件,SW_SHOWNORMAL,返回字符串); //函数执行成功返回 0  

相关阅读 >>

Delphi 实现php的urlencode编码效果

cnvcl 组件包

Delphi 编译发布安卓的app名字问题

Delphi xe5 android平台 调用 webservice

Delphi获取flash文件的影片时长,原始尺寸,帧数等信息

Delphi中对url进行编码和解码

Delphi tapplication.onexception

强大的Delphi rtti--兼谈需要了解多种开发语言

Delphi多级指针

Delphi 文件路径相关的字符串操作

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...