delphi CONSOLE 控制台程序执行系统命令获取结果  
官方Delphi 学习QQ群: 682628230(三千人)
频道

delphi CONSOLE 控制台程序执行系统命令获取结果


{$APPTYPE CONSOLE}


uses

  SysUtils, Classes, Windows;


procedure ReadOutputFromExternalProcess(const ApplicationName, CommandLine: string; Stream: TStream);

const

  PipeSecurityAttributes: TSecurityAttributes = (

    nLength: SizeOf(PipeSecurityAttributes);

    bInheritHandle: True

  );

var

  hstdoutr, hstdoutw: THandle;

  StartupInfo: TStartupInfo;

  ProcessInfo: TProcessInformation;

  lpApplicationName: PChar;

  ModfiableCommandLine: string;

  Buffer: array [0..4096-1] of Byte;

  BytesRead: DWORD;

begin

  if ApplicationName='' then begin

    lpApplicationName := nil;

  end else begin

    lpApplicationName := PChar(ApplicationName);

  end;


  ModfiableCommandLine := CommandLine;

  UniqueString(ModfiableCommandLine);


  Win32Check(CreatePipe(hstdoutr, hstdoutw, @PipeSecurityAttributes, 0));

  Try

    Win32Check(SetHandleInformation(hstdoutr, HANDLE_FLAG_INHERIT, 0));//don't inherit read handle of pipe

    ZeroMemory(@StartupInfo, SizeOf(StartupInfo));

    StartupInfo.cb := SizeOf(StartupInfo);

    StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;

    StartupInfo.wShowWindow := SW_HIDE;

    StartupInfo.hStdOutput := hstdoutw;

    StartupInfo.hStdError := hstdoutw;

    if not CreateProcess(

      lpApplicationName,

      PChar(ModfiableCommandLine),

      nil,

      nil,

      True,

      CREATE_NO_WINDOW or NORMAL_PRIORITY_CLASS,

      nil,

      nil,

      StartupInfo,

      ProcessInfo

    ) then begin

      RaiseLastOSError;

    end;

    CloseHandle(ProcessInfo.hProcess);

    CloseHandle(ProcessInfo.hThread);

    CloseHandle(hstdoutw);//close the write end of the pipe so that the process is able to terminate

    hstdoutw := 0;

    while ReadFile(hstdoutr, Buffer, SizeOf(Buffer), BytesRead, nil) and (BytesRead<>0) do begin

      Stream.WriteBuffer(Buffer, BytesRead);

    end;

  Finally

    CloseHandle(hstdoutr);

    if hstdoutw<>0 then begin

      CloseHandle(hstdoutw);

    end;

  End;

end;


procedure Test;

var

  Stream: TFileStream;

begin

  Stream := TFileStream.Create('C:\Desktop\out.txt', fmCreate);

  Try

    ReadOutputFromExternalProcess('', 'cmd /c dir /s C:\Windows\system32', Stream);

  Finally

    Stream.Free;

  End;

end;


begin

  Test;

end.



推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.03841495513916 seconds