我用命令行参数运行程序。我该如何等待它完成运行?
答案 0 :(得分:11)
这是我的回答:(谢谢大家)
uses ShellAPI;
function TForm1.ShellExecute_AndWait(FileName: string; Params: string): bool;
var
exInfo: TShellExecuteInfo;
Ph: DWORD;
begin
FillChar(exInfo, SizeOf(exInfo), 0);
with exInfo do
begin
cbSize := SizeOf(exInfo);
fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT;
Wnd := GetActiveWindow();
exInfo.lpVerb := 'open';
exInfo.lpParameters := PChar(Params);
lpFile := PChar(FileName);
nShow := SW_SHOWNORMAL;
end;
if ShellExecuteEx(@exInfo) then
Ph := exInfo.hProcess
else
begin
ShowMessage(SysErrorMessage(GetLastError));
Result := true;
exit;
end;
while WaitForSingleObject(exInfo.hProcess, 50) <> WAIT_OBJECT_0 do
Application.ProcessMessages;
CloseHandle(Ph);
Result := true;
end;
答案 1 :(得分:7)
如果我正确理解您的问题,您希望在命令行中执行程序并在应用程序中而不是在控制台窗口中捕获其输出。为此,您可以使用pipes读取输出。以下是一个示例源代码:
答案 2 :(得分:4)
使用DSiWin32:
sl := TStringList.Create;
if DSiExecuteAndCapture('cmd.exe /c dir', sl, 'c:\test', exitCode) = 0 then
// exec error
else
// use sl
sl.Free;
答案 3 :(得分:2)
好的,获取命令行参数,使用
ParamCount
:返回在命令行上传递给程序的参数数量。
ParamStr
:返回索引请求的特定参数。
Running Dephi Applications With Parameters
现在,如果您的意思是读取和写入控制台,则使用
WriteLn
:将一行文字写入控制台。
ReadLn
:从控制台读取一行文本作为字符串。
Delphi Basics
答案 4 :(得分:2)
如果您想要执行命令行可执行文件,并获得此exe写入控制台的响应,最简单的方法是从批处理文件调用exe并使用{将输出重定向到另一个文件{1}},然后读取该文件。
例如,如果您需要执行“dir”命令并获取其输出,您可以拥有一个名为>
的批处理文件,其中包含以下内容:
getdir.bat
您可以使用API函数ShellExecute执行该批处理文件。你可以阅读它http://delphi.about.com/od/windowsshellapi/a/executeprogram.htm
然后你可以读取输出文件,甚至使用类似TStringList的东西:
@echo off
dir c:\users\myuser\*.* > output.txt