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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 12:31:25  来源:igfitidea点击:

How to determine if an process is the currently active / foreground application

windowsprocess

提问by Jan Gressmann

I'd like to be able to query some function and give it a processID or processName - It then should return trueor falseon 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.

GetForegroundWindowGetWindowThreadProcessId应该可以让您获得此信息。

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 应用程序等。请注意,这仅适用于在调用桌面和会话上运行的应用程序 - 您可以例如,不要使用它来确定另一个用户的应用程序是否在前台。