天天看點

[delphi]運作cmd指令,并取得輸出字元

  1. procedure CheckResult(b: Boolean);  
  2. begin  
  3.   if not b then  
  4.     raise Exception.Create(SysErrorMessage(GetLastError));  
  5. end;  
  6. function RunDOS(const CommandLine: string): string;  
  7. var  
  8.   HRead, HWrite: THandle;  
  9.   StartInfo: TStartupInfo;  
  10.   ProceInfo: TProcessInformation;  
  11.   b: Boolean;  
  12.   sa: TSecurityAttributes;  
  13.   inS: THandleStream;  
  14.   sRet: TStrings;  
  15.   Result := '';  
  16.   FillChar(sa, sizeof(sa), 0);  
  17. //設定允許繼承,否則在NT和2000下無法取得輸出結果  
  18.   sa.nLength := sizeof(sa);  
  19.   sa.bInheritHandle := True;  
  20.   sa.lpSecurityDescriptor := nil;  
  21.   b := CreatePipe(HRead, HWrite, @sa, 0);  
  22.   CheckResult(b);  
  23.   FillChar(StartInfo, SizeOf(StartInfo), 0);  
  24.   StartInfo.cb := SizeOf(StartInfo);  
  25.   StartInfo.wShowWindow := SW_HIDE;  
  26. //使用指定的句柄作為标準輸入輸出的檔案句柄,使用指定的顯示方式  
  27.   StartInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;  
  28.   StartInfo.hStdError := HWrite;  
  29.   StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); //HRead;  
  30.   StartInfo.hStdOutput := HWrite;  
  31.   b := CreateProcess(nil, //lpApplicationName: PChar  
  32.     PChar(CommandLine), //lpCommandLine: PChar  
  33.     nil, //lpProcessAttributes: PSecurityAttributes  
  34.     nil, //lpThreadAttributes: PSecurityAttributes  
  35.     True, //bInheritHandles: BOOL  
  36.     CREATE_NEW_CONSOLE,  
  37.     nil,  
  38.     StartInfo,  
  39.     ProceInfo);  
  40.   WaitForSingleObject(ProceInfo.hProcess, INFINITE);  
  41.   inS := THandleStream.Create(HRead);  
  42.   if inS.Size > 0 then  
  43.   begin  
  44.     sRet := TStringList.Create;  
  45.     sRet.LoadFromStream(inS);  
  46.     Result := sRet.Text;  
  47.     sRet.Free;  
  48.   end;  
  49.   inS.Free;  
  50.   CloseHandle(HRead);  
  51.   CloseHandle(HWrite);