为什么 hasExited 抛出“System.ComponentModel.Win32Exception"? [英] Why did hasExited throw 'System.ComponentModel.Win32Exception'?

查看:56
本文介绍了为什么 hasExited 抛出“System.ComponentModel.Win32Exception"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 ShellExecuteEx 成功运行一个新进程,但是如果我访问 HasExited 属性,则会引发 Win32Exception.这是什么异常,如何检查进程是否处于活动状态?

I can successfully run a new process using ShellExecuteEx, but if I access the HasExited property, a Win32Exception is thrown. What is this exception and how do I check if the process is alive?

ShellExecuteEx(ref info);
clientProcessId = NativeMethods.GetProcessId(info.hProcess);
Process clientProcess = Process.GetProcessById((int)clientProcessId);

if (clientProcess.HasExited) //<---- throws Win32Exception, but the process is alive! I can see its window
{
   //run new one
}

谢谢

推荐答案

有关信息,您是否将 fMask 设置为 SEE_MASK_NOCLOSEPROCESS,以便 hProcess 有效?

For info, did you set fMask to SEE_MASK_NOCLOSEPROCESS, so that hProcess is valid?

另外,你为什么要调用 ShellExecuteEx,为什么不使用 Process.Start w/ProcessStartInfo,它会为你处理 ShellExecuteEx?

Also, why are you P/Invoke'ing to ShellExecuteEx, why not use Process.Start w/ ProcessStartInfo, which will handle ShellExecuteEx for you?

由于您正在执行 runas,您只能获得句柄上的 SYNCHRONIZE 访问权限,而不是 PROCESS_QUERY_INFORMATION 访问权限,因此 GetExitCodeProcess 失败,导致 hasEnded 抛出 Win32 异常.

Since you are doing runas, you only get SYNCHRONIZE access on the handle, not PROCESS_QUERY_INFORMATION access, hence GetExitCodeProcess fails, which results in hasEnded throwing a Win32 exception.

作为一种解决方法,您可以在超时为零的情况下 P/Invoke WaitForSingleObject 以查看进程是否已退出.

As a workaround, you could P/Invoke WaitForSingleObject with a timeout of zero to see if the process has exited.

这篇关于为什么 hasExited 抛出“System.ComponentModel.Win32Exception"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆