windows 如何确定一个进程是否是当前活动/前台应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/884256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to determine if an process is the currently active / foreground application
提问by Jan Gressmann
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.
我希望能够查询某个函数并给它一个 processID 或 processName - 然后它应该返回true
或者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
.
因此,即对 Firefox 的查询将返回true
(因为现在我在 FireFox 中,输入此内容)并且其他所有内容都应返回false
。
Is that even possible for every type of application (.net, java/swing, pure c++/win32-ui)?
对于每种类型的应用程序(.net、java/swing、纯 c++/win32-ui),这甚至可能吗?
- This question is for Windows only.
- 此问题仅适用于 Windows。
回答by Michael
GetForegroundWindowand GetWindowThreadProcessIdshould let you get this information.
GetForegroundWindow和GetWindowThreadProcessId应该可以让您获得此信息。
i.e., if you know the pid just check it against a function like this:
即,如果您知道 pid,只需根据这样的函数检查它:
bool IsForegroundProcess(DWORD pid)
{
HWND hwnd = GetForegroundWindow();
if (hwnd == NULL) return false;
DWORD foregroundPid;
if (GetWindowThreadProcessId(hwnd, &foregroundPid) == 0) return false;
return (foregroundPid == pid);
}
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.
这适用于在某种程度上使用核心 Win32 库的任何应用程序 - 这将包括 Windows 窗体、WPF、本机 Win32 应用程序等。请注意,这仅适用于在调用桌面和会话上运行的应用程序 - 您可以例如,不要使用它来确定另一个用户的应用程序是否在前台。