您现在的位置:首页 >> API >> API >> 内容

Delphi执行控制台命令并获取结果

时间:2011/9/3 14:52:25 点击:

  核心提示:procedure RunDosCommand(Que:String;EnMemo:TMemo); const CUANTOBUFFER = 2000; var Seguridades : TSecu...
procedure RunDosCommand(Que:String;EnMemo:TMemo);
  const
    
CUANTOBUFFER = 2000;
  var
   
Seguridades         : TSecurityAttributes;
    PaLeer,PaEscribir   : THandle;
    start          : TStartUpInfo;
    ProcessInfo         : TProcessInformation;
    Buffer          : Pchar;
    BytesRead          : DWord;
    CuandoSale          : DWord;
  begin
    with
Seguridades do
    begin
     
nlength          := SizeOf(TSecurityAttributes);
      binherithandle := true;
      lpsecuritydescriptor := nil;
    end;
    {Creamos el pipe...}
   
if Createpipe (PaLeer, PaEscribir, @Seguridades, 0) then
    begin
     
Buffer  := AllocMem(CUANTOBUFFER + 1);
      FillChar(Start,Sizeof(Start),#0);
      start.cb          := SizeOf(start);
      start.hStdOutput  := PaEscribir;
      start.hStdInput   := PaLeer;
      start.dwFlags     := STARTF_USESTDHANDLES +
          STARTF_USESHOWWINDOW;
      start.wShowWindow := SW_HIDE;
      if CreateProcess(nil,
         PChar(Que),
         @Seguridades,
         @Seguridades,
         true,
         NORMAL_PRIORITY_CLASS,
         nil,
         nil,
         start,
         ProcessInfo)
      then
        begin
         
{Espera a que termine la ejecucion}
         
repeat
         
CuandoSale := WaitForSingleObject( ProcessInfo.hProcess,100);
          Application.ProcessMessages;
          until (CuandoSale <> WAIT_TIMEOUT);
          {Leemos la Pipe}
         
repeat
         
BytesRead := 0;
          {Llenamos un troncho de la pipe, igual a nuestro buffer}
         
ReadFile(PaLeer,Buffer[0],CUANTOBUFFER,BytesRead,nil);
          {La convertimos en una string terminada en cero}
         
Buffer[BytesRead]:= #0;
          {Convertimos caracteres DOS a ANSI}
         
OemToAnsi(Buffer,Buffer);
          EnMemo.Text := EnMemo.text + String(Buffer);
          until (BytesRead < CUANTOBUFFER);
        end;
      FreeMem(Buffer);
      CloseHandle(ProcessInfo.hProcess);
      CloseHandle(ProcessInfo.hThread);
      CloseHandle(PaLeer);
      CloseHandle(PaEscribir);
    end;
  end;

作者:网络 来源:转载
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
本类推荐
  • 没有
本类固顶
  • 没有
  • 盒子文章(www.2ccc.com) © 2024 版权所有 All Rights Reserved.
  • 沪ICP备05001939号