delphi 利用CreateProcess 执行cmd 获取结果  
官方Delphi 学习QQ群: 682628230(三千人)\n
频道

delphi 利用CreateProcess 执行cmd 获取结果


function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string;  { Run a DOS program and retrieve its output dynamically while it is running. }

var

  SecAtrrs: TSecurityAttributes;

  StartupInfo: TStartupInfo;

  ProcessInfo: TProcessInformation;

  StdOutPipeRead, StdOutPipeWrite: THandle;

  WasOK: Boolean;

  pCommandLine: array[0..255] of AnsiChar;

  BytesRead: Cardinal;

  WorkDir: string;

  Handle: Boolean;

begin

  Result := '';

  with SecAtrrs do begin

    nLength := SizeOf(SecAtrrs);

    bInheritHandle := True;

    lpSecurityDescriptor := nil;

  end;

  CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SecAtrrs, 0);

  try

    with StartupInfo do

    begin

      FillChar(StartupInfo, SizeOf(StartupInfo), 0);

      cb := SizeOf(StartupInfo);

      dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;

      wShowWindow := SW_HIDE;

      hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin

      hStdOutput := StdOutPipeWrite;

      hStdError := StdOutPipeWrite;

    end;

    WorkDir := Work;

    Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine),

                            nil, nil, True, 0, nil,

                            PChar(WorkDir), StartupInfo, ProcessInfo);

    CloseHandle(StdOutPipeWrite);

    if Handle then

      try

        repeat

          WasOK := windows.ReadFile(StdOutPipeRead, pCommandLine, 255, BytesRead, nil);

          if BytesRead > 0 then

          begin

            pCommandLine[BytesRead] := #0;

            Result := Result + pCommandLine;

          end;

        until not WasOK or (BytesRead = 0);

        WaitForSingleObject(ProcessInfo.hProcess, INFINITE);

      finally

        CloseHandle(ProcessInfo.hThread);

        CloseHandle(ProcessInfo.hProcess);

      end;

  finally

    CloseHandle(StdOutPipeRead);

  end;

end;



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

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

执行时间: 0.059069871902466 seconds