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 实现简易语音发音(基于tts方式)

Delphi 一个定时器timer1相关的简单例子

shellexecute的多种用法

Delphi 利用http的post方法做个在线翻译的小工

Delphi 清空目录以及子目录

Delphi with 语句的妙用

Delphi源码获取网络图片缓存的地址

Delphi 让combobox只允许输入数字和回车键以及Delphi key值表

Delphi获取千千静听歌词下载地址源码

Delphi twebbrowser控件禁用鼠标右键

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



打赏

取消

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

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

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

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

评论

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