procedure Redirect(const aExecuteFile:string;
const aInputFile :string;
const aOutputFile :string);
var
SI: TStartupInfo;
PI: TProcessInformation;
hInput, hOutput : THandle;
WorkDir: string;
bOk: Boolean;
begin
hInput := FileOpen(aInputFile, fmOpenRead);
hOutput:= FileCreate(aOutputFile);
try
// Make child process use StdOutPipeWrite as standard out,
// and make sure itdo
es not show on screen.
with SIdo
begin
FillChar(SI, SizeOf(SI), 0);
cb := SizeOf(SI);
dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow := SW_HIDE;
hStdInput := hInput;
hStdOutput:= hOutput;
hStdError := hOutput;
end;
// launch the command line compiler
WorkDir := ExtractFilePath(aExecuteFile);
bOK := CreateProcess(nil, PChar(aExecuteFile), nil, nil, True, 0, nil,
PChar(WorkDir), SI, PI);
try
// if process could be created then
handle its output
if not bOK then
raise Exception.Create('Could not run ' + aExecuteFile);
WaitForSingleObject(PI.hProcess, INFINITE);
finally
// Close all remaining handles
CloseHandle(PI.hThread);
CloseHandle(PI.hProcess);
end;
finally
FileClose(hInput);
FileClose(hOutput);
end;
end;
看看上面的代码, 你应该明白重定向的含义了. 你只要得到合适的句柄, 可以把输入输
出重定向到你想要的地方. 句柄可以是文件, 也可以是管道, 你只要指定好
hStdInput(标准输入),hStdOutput(标准输出),hStdError(标准错误) 就可以了.