如何正确使用 WaitForSingleObject 方法来等待外部程序终止?
我正在尝试启动具有提升状态的外部应用程序,并等到它退出后再继续:
var
FProcess: THandle;
ExecInfo: TShellExecuteInfo;
begin
FillChar(ExecInfo, SizeOf(ExecInfo), 0);
with ExecInfo do
begin
cbSize := SizeOf(ExecInfo);
fMask := 0;
Wnd := AWindow;
lpVerb := 'runas';
lpFile := PChar(APath);
lpParameters := PChar(AParams);
lpDirectory := PChar(AWorkDir);
nShow := SW_NORMAL;
end;
Result := ShellExecuteEx(@ExecInfo);
if Wait then
begin
while WaitForSingleObject(ExecInfo.hProcess, INFINITE) <> WAIT_TIMEOUT do
Application.ProcessMessages;
end;
此启动,但它只是一直等待。即使被调用程序退出后,调用程序也不会继续调用 WaitForSingleObject。
我尝试过 WAIT_OBJECT_0 而不是 WAIT_TIMEOUT,但我遇到了同样的问题。我在这里做错了什么?
I'm trying to launch an external application with elevated status, and wait until it exits before continuing:
var
FProcess: THandle;
ExecInfo: TShellExecuteInfo;
begin
FillChar(ExecInfo, SizeOf(ExecInfo), 0);
with ExecInfo do
begin
cbSize := SizeOf(ExecInfo);
fMask := 0;
Wnd := AWindow;
lpVerb := 'runas';
lpFile := PChar(APath);
lpParameters := PChar(AParams);
lpDirectory := PChar(AWorkDir);
nShow := SW_NORMAL;
end;
Result := ShellExecuteEx(@ExecInfo);
if Wait then
begin
while WaitForSingleObject(ExecInfo.hProcess, INFINITE) <> WAIT_TIMEOUT do
Application.ProcessMessages;
end;
This launches, but it just keeps waiting. The calling program never continues past the call to WaitForSingleObject, even after the called program exits.
I've tried WAIT_OBJECT_0 instead of WAIT_TIMEOUT, but I have the same problem. What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
代码
应该做什么?这是一个无限循环。
直接使用
即可。是的,您需要
获取进程句柄。
What the code
is supposed to do? It is an infinite loop.
Use just
instead. And yes, you need
to obtain the process handle.
你的代码被破坏了。您没有将
SEE_MASK_NOCLOSEPROCESS
标志传递给ShellExecuteEx()
,因此它不会向您返回有效的进程句柄,并且您的循环会忽略WaitForSingleObject 的错误()
告诉你正因为如此,所以你最终陷入了无限循环。试试这个:
Your code is broken. You are not passing the
SEE_MASK_NOCLOSEPROCESS
flag toShellExecuteEx()
, so it will not return a valid process handle to you, and your loop is ignoring the errors thatWaitForSingleObject()
tells you because of that, so you end up in an endless loop.Try this instead:
如果您阅读MSDN 中有关 ShellExecuteEx 的说明,你会看到这个:
也就是说,您根本没有有效的句柄。您需要按照上面的说明设置 fMask。
If you read description of ShellExecuteEx in MSDN, you will see this:
I.e. you simply don't have a valid handle. You need to set fMask as written above.