zoukankan      html  css  js  c++  java
  • [转]Delphi调用cmd并取得输出文本

    //转自http://www.oschina.net/code/snippet_136241_3980 

    1
    procedure CheckResult(b: Boolean); 2 begin 3 if not b then 4 raise Exception.Create(SysErrorMessage(GetLastError)); 5 end; 6 7 function RunDOS(const CommandLine: string): string; 8 var 9 HRead, HWrite: THandle; 10 StartInfo: TStartupInfo; 11 ProceInfo: TProcessInformation; 12 b: Boolean; 13 sa: TSecurityAttributes; 14 inS: THandleStream; 15 sRet: TStrings; 16 begin 17 Result := ''; 18 FillChar(sa, sizeof(sa), 0); 19 //设置允许继承,否则在NT和2000下无法取得输出结果 20 sa.nLength := sizeof(sa); 21 sa.bInheritHandle := True; 22 sa.lpSecurityDescriptor := nil; 23 b := CreatePipe(HRead, HWrite, @sa, 0); 24 CheckResult(b); 25 26 FillChar(StartInfo, SizeOf(StartInfo), 0); 27 StartInfo.cb := SizeOf(StartInfo); 28 StartInfo.wShowWindow := SW_HIDE; 29 //使用指定的句柄作为标准输入输出的文件句柄,使用指定的显示方式 30 StartInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; 31 StartInfo.hStdError := HWrite; 32 StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); //HRead; 33 StartInfo.hStdOutput := HWrite; 34 35 b := CreateProcess(nil, //lpApplicationName: PChar 36 PChar(CommandLine), //lpCommandLine: PChar 37 nil, //lpProcessAttributes: PSecurityAttributes 38 nil, //lpThreadAttributes: PSecurityAttributes 39 True, //bInheritHandles: BOOL 40 CREATE_NEW_CONSOLE, 41 nil, 42 nil, 43 StartInfo, 44 ProceInfo); 45 46 CheckResult(b); 47 WaitForSingleObject(ProceInfo.hProcess, INFINITE); 48 49 inS := THandleStream.Create(HRead); 50 if inS.Size > 0 then 51 begin 52 sRet := TStringList.Create; 53 sRet.LoadFromStream(inS); 54 Result := sRet.Text; 55 sRet.Free; 56 end; 57 inS.Free; 58 59 CloseHandle(HRead); 60 CloseHandle(HWrite); 61 end;
  • 相关阅读:
    Algs4-2.3.11快排遇与切分值相同时继续扫描是平方级
    使用kubeadm搭建Kubernetes集群
    kubernetes发布解释型语言应用的最佳实践
    docker化php项目发布方式
    linux服务器免密钥登录
    cp 递归复制时 复制实际文件而不是链接文件
    nginx配置http访问自动跳转到https
    nfs服务器
    nginx防止恶意域名解析
    如何建立自己的知识体系?(摘)
  • 原文地址:https://www.cnblogs.com/laymond/p/3945120.html
Copyright © 2011-2022 走看看