【发布时间】:2018-11-27 16:16:51
【问题描述】:
我正在创建一个需要检查某个进程的响应的应用程序。
System.Diagnostics.Responding 无法正常工作。所以我正在尝试使用 Windows API 找到解决方案。
我已经尝试过这样的 SendMessageTimeOut:
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
IntPtr hWnd,
uint msg,
UIntPtr wParam,
IntPtr lParam,
uint flags,
uint timeout,
out IntPtr pdwResult);
public static bool IsResponding(Process process)
{
IntPtr hProcess = IntPtr.Zero;
try
{
hProcess = OpenProcess(
ProcessAccessFlags.QueryInformation | ProcessAccessFlags.DuplicateHandle | ProcessAccessFlags.Synchronize,
false,
(uint)process.Id
);
if (hProcess == IntPtr.Zero)
return false;
IntPtr hResult = SendMessageTimeout(hProcess, 13, UIntPtr.Zero, IntPtr.Zero, SMTO_ABORTIFHUNG, 2000, out IntPtr pdwResult);
return hResult != IntPtr.Zero;
}
catch
{
return false;
}
finally
{
if (hProcess != IntPtr.Zero)
CloseHandle(hProcess);
}
}
其他尝试是使用 IsHungAppWindow。
[DllImport("user32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsHungAppWindow(IntPtr hwnd);
我真的不知道为什么它总是告诉我应用程序没有响应。
我认为,我的 PInvokes 工作正常,不要随时扔。 OpenProcess 也在工作。
我创建了一个 WPF 应用程序,它可以每 15 秒响应一次,也可以不响应一次。任务管理器无法正常响应,但我的应用程序没有。
我做错了什么?我读到的所有关于建议我使用这两个功能的信息。
【问题讨论】:
-
看看这篇文章,我认为它与您遇到的问题非常相似。 stackoverflow.com/questions/3500634/…
-
@ShawnLehner 我已经读过,但对我没有帮助:(
-
请注意,Process.Responding 还使用具有 5000 超时时间的 SendMessageTimeout:github.com/Microsoft/referencesource/blob/master/System/…,因此您可以 1) 了解它是如何完成的,并且 2) 无论如何它可能对您不利。