标准办法:<br>function TForm1.RunCaptured(const _dirName, _exeName, _cmdLine: string): Boolean; <br>var <br> start: TStartupInfo; <br> procInfo: TProcessInformation; <br> tmpName: string; <br> tmp: Windows.THandle; <br> tmpSec: TSecurityAttributes; <br> res: TStringList; <br> return: Cardinal; <br>begin <br> Result := False; <br> try <br> { Set a temporary file } <br> tmpName := 'Test.tmp'; <br> FillChar(tmpSec, SizeOf(tmpSec), #0); <br> tmpSec.nLength := SizeOf(tmpSec); <br> tmpSec.bInheritHandle := True; <br> tmp := Windows.CreateFile(PChar(tmpName), <br> Generic_Write, File_Share_Write, <br> @tmpSec, Create_Always, File_Attribute_Normal, 0); <br> try <br> FillChar(start, SizeOf(start), #0); <br> start.cb := SizeOf(start); <br> start.hStdOutput := tmp; <br> start.dwFlags := StartF_UseStdHandles or StartF_UseShowWindow; <br> start.wShowWindow := SW_Minimize; <br> { Start the program } <br> if CreateProcess(nil, PChar(_exeName + ' ' + _cmdLine), nil, nil, True, <br> 0, nil, PChar(_dirName), start, procInfo) then <br> begin <br> SetPriorityClass(procInfo.hProcess, Idle_Priority_Class); <br> WaitForSingleObject(procInfo.hProcess, Infinite); <br> GetExitCodeProcess(procInfo.hProcess, return); <br> Result := (return = 0); <br> CloseHandle(procInfo.hThread); <br> CloseHandle(procInfo.hProcess); <br> Windows.CloseHandle(tmp); <br> { Add the output } <br> res := TStringList.Create; <br> try <br> res.LoadFromFile(tmpName); <br> Memo1.Lines.AddStrings(res); <br> finally <br> res.Free; <br> end; <br> Windows.DeleteFile(PChar(tmpName)); <br> end <br> else <br> begin <br> Application.MessageBox(PChar(SysErrorMessage(GetLastError())), <br> 'RunCaptured Error', MB_OK); <br> end; <br> except <br> Windows.CloseHandle(tmp); <br> Windows.DeleteFile(PChar(tmpName)); <br> raise; <br> end; <br> finally <br> end; <br>end; <br><br><br>// 例子: <br><br>procedure TForm1.Button1Click(Sender: TObject); <br>begin <br> RunCaptured('C:/', 'cmd.exe', '/c dir'); <br>end;