如何确定一个进程是否是当前活动/前台应用程序 [英] How to determine if an process is the currently active / foreground application
问题描述
我希望能够查询某个函数并给它一个 processID 或 processName - 然后它应该返回 true
或 false
是否该进程在前景与否.
I'd like to be able to query some function and give it a processID or processName - It then should return true
or false
on wether that process is in the foreground or not.
因此,即对 Firefox 的查询将返回 true
(因为现在我在 FireFox 中,输入此内容),其他所有内容都应返回 false
.
So i.e. the query for Firefox would return true
(because right now I'm in FireFox, typing this) and everything else should return false
.
这是否适用于所有类型的应用程序(.net、java/swing、纯 c++/win32-ui)?
Is that even possible for every type of application (.net, java/swing, pure c++/win32-ui)?
- 此问题仅适用于 Windows.
推荐答案
GetForegroundWindow 和 GetWindowThreadProcessId 应该让你得到这个信息.
GetForegroundWindow and GetWindowThreadProcessId should let you get this information.
即,如果您知道 pid,只需根据这样的函数检查它:
i.e., if you know the pid just check it against a function like this:
bool IsForegroundProcess(DWORD pid)
{
HWND hwnd = GetForegroundWindow();
if (hwnd == NULL) return false;
DWORD foregroundPid;
if (GetWindowThreadProcessId(hwnd, &foregroundPid) == 0) return false;
return (foregroundPid == pid);
}
这适用于在某种程度上使用核心 Win32 库的任何应用程序 - 这将包括 Windows 窗体、WPF、本机 Win32 应用程序等.请注意,这仅适用于在调用桌面和会话上运行的应用程序 -例如,您不能使用它来确定另一个用户的应用程序是否在前台.
This will work for any application that uses the core Win32 library at some level - this'll include Windows Forms, WPF, native Win32 applications, etc. Note this'll only work for applications running on the calling desktop and session - you can't use this to determine if another user's application is in the foreground, for instance.
这篇关于如何确定一个进程是否是当前活动/前台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!