我有一个用 Delphi XE2 编写的 VCL 应用程序,它需要执行一个命令行程序(也是用 Delphi XE2 编写的)并获取它输出的文本。我目前正在使用以下代码,该代码基于此处找到的代码:Getting output from a shell/dos app into a Delphi app
function GetDosOutput(ACommandLine : string; AWorkingDirectory : string): string;
var
SecurityAttributes : TSecurityAttributes;
StartupInfo : TStartupInfo;
ProcessInformation: TProcessInformation;
StdOutPipeRead, StdOutPipeWrite: THandle;
WasOK: Boolean;
Buffer: array[0..255] of AnsiChar;
BytesRead: Cardinal;
Handle: Boolean;
begin
Result := '';
SecurityAttributes.nLength := SizeOf(TSecurityAttributes);
SecurityAttributes.bInheritHandle := True;
SecurityAttributes.lpSecurityDescriptor := nil;
CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SecurityAttributes, 0);
try
FillChar(StartupInfo, SizeOf(TStartupInfo), 0);
StartupInfo.cb := SizeOf(TStartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
StartupInfo.wShowWindow := SW_HIDE;
StartupInfo.hStdInput := StdOutPipeRead;
StartupInfo.hStdOutput := StdOutPipeWrite;
StartupInfo.hStdError := StdOutPipeWrite;
FillChar(ProcessInformation, SizeOf(ProcessInformation), 0);
Handle := CreateProcess(
nil,
PChar(ACommandLine),
nil,
nil,
True,
0,
nil,
PChar(AWorkingDirectory),
StartupInfo,
ProcessInformation
);
CloseHandle(StdOutPipeWrite);
if Handle then
try
repeat
WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil);
if BytesRead > 0 then
begin
Buffer[BytesRead] := #0;
Result := Result + Buffer;
end;
until not WasOK or (BytesRead = 0);
WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
finally
CloseHandle(ProcessInformation.hThread);
CloseHandle(ProcessInformation.hProcess);
end;
finally
CloseHandle(StdOutPipeRead);
end;
end;
这适用于大多数版本的 Windows。不幸的是,我们最近注意到它不适用于 Windows XP。对 WaitForSingleObject 的调用永远不会返回。我尝试用较小的值(例如 15000)替换第二个参数 INFINITE,但这似乎没有任何区别。在任务管理器中,我可以看到,在调用 GetDosOutput 之后,命令行程序实际上正在运行。如果我结束 VCL 应用程序,那么命令行程序似乎成功地完成了它的工作(正如它输出我所期望的文件的事实所证明的那样)。我还注意到,如果我从 StartupInfo.dwFlags 中删除 STARTF_USESTDHANDLES,命令行程序会正常运行并且 WaitForSingleObject 会迅速返回;但是我显然无法获得程序返回的文本。
有人对我如何在 Windows XP 上运行有建议吗?