获取DOS命令的返回值.

摘要:
procedureCheckResult(b:布尔值);beginifnotbthenraiseException。创建(SysErrorMessage(GetLastError));结束;函数RunDOS(constProg,CommandLine,Dir:string;varExitCode:DWORD):字符串;varHRead,H写入:THandl
procedure CheckResult(b: Boolean);
begin
  
if not b then
    
raise Exception.Create(SysErrorMessage(GetLastError));
end;

function RunDOS(const Prog, CommandLine, Dir: stringvar 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;

function GetDosOutput(const CommandLine: string): string;
var
  SA: TSecurityAttributes;
  SI: TStartupInfo;
  PI: TProcessInformation;
  StdOutPipeRead, StdOutPipeWrite: THandle;
  WasOK: Boolean;
  Buffer: 
array[0..255of Char;
  BytesRead: Cardinal;
  WorkDir, Line: 
string;
begin
  Application.ProcessMessages;
  
with SA do
  
begin
    nLength :
= SizeOf(SA);
    bInheritHandle :
= True;
    lpSecurityDescriptor :
= nil;
  
end;
          
//   create   pipe   for   standard   output   redirection
  CreatePipe(StdOutPipeRead, 
//   read   handle
    StdOutPipeWrite, 
//   write   handle
    @SA, 
//   security   attributes
    
0 //   number   of   bytes   reserved   for   pipe   -   0   default
    );
  
try
              
//   Make   child   process   use   StdOutPipeWrite   as   standard   out,
              
//   and   make   sure   it   does   not   show   on   screen.
    
with SI do
    
begin
      FillChar(SI, SizeOf(SI), 
0);
      cb :
= SizeOf(SI);
      dwFlags :
= STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
      wShowWindow :
= SW_HIDE;
      hStdInput :
= GetStdHandle(STD_INPUT_HANDLE); //   don't   redirect   stdinput
      hStdOutput := StdOutPipeWrite;
      hStdError :
= StdOutPipeWrite;
    
end;

              
//   launch   the   command   line   compiler
    WorkDir :
= ExtractFilePath(CommandLine);
    WasOK :
= CreateProcess(nil, PChar(CommandLine), nilnil, True, 0nil,
      PChar(WorkDir), SI, PI);

              
//   Now   that   the   handle   has   been   inherited,   close   write   to   be   safe.
              
//   We   don't   want   to   read   or   write   to   it   accidentally.
    CloseHandle(StdOutPipeWrite);
              
//   if   process   could   be   created   then   handle   its   output
    
if not WasOK then
      
raise Exception.Create('Could   not   execute   command   line!')
    
else
    
try
                      
//   get   all   output   until   dos   app   finishes
      Line :
= '';
      
repeat
                          
//   read   block   of   characters   (might   contain   carriage   returns   and   line   feeds)
        WasOK :
= ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil);

                          
//   has   anything   been   read?
        
if BytesRead > 0 then
        
begin
                              
//   finish   buffer   to   PChar
          Buffer[BytesRead] :
= #0;
                              
//   combine   the   buffer   with   the   rest   of   the   last   run
          Line :
= Line + Buffer;
        
end;
      
until not WasOK or (BytesRead = 0);
                      
//   wait   for   console   app   to   finish   (should   be   already   at   this   point)
      WaitForSingleObject(PI.hProcess, INFINITE);
    
finally
                      
//   Close   all   remaining   handles
      CloseHandle(PI.hThread);
      CloseHandle(PI.hProcess);
    
end;
  
finally
    result :
= Line;
    CloseHandle(StdOutPipeRead);
  
end;
end;


procedure TForm1.btn1Click(Sender: TObject);
var
  hReadPipe, hWritePipe: THandle;
  si: STARTUPINFO;
  lsa: SECURITY_ATTRIBUTES;
  pi: PROCESS_INFORMATION;
  cchReadBuffer: DWORD;
  ph: PChar;
  fname: PChar;
begin
  fname :
= allocmem(255);
  ph :
= AllocMem(5000);
  lsa.nLength :
= sizeof(SECURITY_ATTRIBUTES);
  lsa.lpSecurityDescriptor :
= nil;
  lsa.bInheritHandle :
= True;

  
if CreatePipe(hReadPipe, hWritePipe, @lsa, 0= false then
  
begin
    ShowMessage(
'Can   not   create   pipe!');
    exit;
  
end;
  fillchar(si, sizeof(STARTUPINFO), 
0);
  si.cb :
= sizeof(STARTUPINFO);
  si.dwFlags :
= (STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW);
  si.wShowWindow :
= SW_SHOW;
  si.hStdOutput :
= hWritePipe;
  StrPCopy(fname, EdtFilename.text);
  
if CreateProcess(nil, fname, nilnil, true, 0nilnil, si, pi) = False then
  
begin
    ShowMessage(
'can   not   create   process');
    FreeMem(ph);
    FreeMem(fname);
    Exit;
  
end;

  
while (true) do
  
begin
    
if not PeekNamedPipe(hReadPipe, ph, 1, @cchReadBuffer, nilnilthen break;
    
if cchReadBuffer <> 0 then
    
begin
      
if ReadFile(hReadPipe, ph^, 4096, cchReadBuffer, nil= false then break;
      ph[cchReadbuffer] :
= chr(0);
      Mmo1.Lines.Add(ph);
    
end
    
else if (WaitForSingleObject(pi.hProcess, 0= WAIT_OBJECT_0then break;
    Sleep(
100);
  
end;

  ph[cchReadBuffer] :
= chr(0);
  Mmo1.Lines.Add(ph);
  CloseHandle(hReadPipe);
  CloseHandle(pi.hThread);
  CloseHandle(pi.hProcess);
  CloseHandle(hWritePipe);
  FreeMem(ph);
  FreeMem(fname);
end;

免责声明:文章转载自《获取DOS命令的返回值.》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇centos系统下安装使用composer教程oracle排序下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

接口返回值结果转换成JSON

接口返回值结果转换成JSON,具体的方法如下: public static String GetJsonValue(String result,intindex,String key){ intindexloc,indexkey; String newstr; indexloc=result.indexOf(...

linux下如何模拟按键输入和模拟鼠标

http://blog.chinaunix.net/u3/94700/showart_2211516.html 查看/dev/input/eventX是什么类型的事件, cat /proc/bus/input/devices设备有着自己特殊的按键键码,我需要将一些标准的按键,比如0-9,X-Z等模拟成标准按键,比如KEY_0,KEY-Z等,所以需要用到按键...

socket选项总结(setsocketopt)

功能描述:        获取或者设置与某个套接字关联的选 项。选项可能存在于多层协议中,它们总会出现在最上面的套接字层。当操作套接字选项时,选项位于的层和选项的名称必须给出。为了操作套接字层的选项,应该 将层的值指定为SOL_SOCKET。为了操作其它层的选项,控制选项的合适协议号必须给出。例如,为了表示一个选项由TCP协议解析,层应该设定为协议 号TC...

Unity3d 跑酷游戏 之Character Controller篇

                                              unity3d  Character Controller                                                                                       @by  广州小龙       ...

线程属性--十分重要的概念

http://blog.chinaunix.net/uid-23193900-id-3346199.html 一.线程属性 线程具有属性,用pthread_attr_t表示,在对该结构进行处理之前必须进行初始化,在使用后需要对其去除初始化。我们用pthread_attr_init函数对其初始化,用pthread_attr_destroy对其去除初始化。...

RxJava入门

项目小版本上线,抽空简单学习了下久仰大名的RxJava 一、引入 个人觉得rxjava的特点: 强大灵活的事件流处理(多线程/多事件/复合对象) 强大灵活优雅简洁的异步 链式调用 可自动Lambda化   实现:RxJava 是通过一种扩展的观察者模式来实现的 类比 类比 实际 实际 职责 演讲者 Button (可)被订阅者 (同右)...