注意:有一个非常相似的问题,但它是 WPF 特定的;这个不是。
如何确定当前应用程序是否已激活(即具有焦点)?
这有效:
/// <summary>Returns true if the current application has focus, false otherwise</summary>
public static bool ApplicationIsActivated()
{
var activatedHandle = GetForegroundWindow();
if (activatedHandle == IntPtr.Zero) {
return false; // No window is currently activated
}
var procId = Process.GetCurrentProcess().Id;
int activeProcId;
GetWindowThreadProcessId(activatedHandle, out activeProcId);
return activeProcId == procId;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
它的优点是线程安全,不需要主窗体(或其句柄),并且不是 WPF 或 WinForms 特定的。它将与子窗口一起使用(甚至是在单独线程上创建的独立窗口)。此外,还需要零设置。
缺点是它使用了一点 P/Invoke,但我可以接受:-)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)