8

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.

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.



Is that even possible for every type of application (.net, java/swing, pure c++/win32-ui)?

  • This question is for Windows only.
Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
Jan Gressmann
  • 5,481
  • 4
  • 32
  • 26

1 Answers1

10

GetForegroundWindow and GetWindowThreadProcessId should let you get this information.

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);
}

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.

JWWalker
  • 22,385
  • 6
  • 55
  • 76
Michael
  • 54,279
  • 5
  • 125
  • 144
  • Thanks, do you know if this works for DirectX / OpenGL applications? – Jan Gressmann May 19 '09 at 18:27
  • I think it might . . . D3D apps have a focus window or device window that might work with this here. – Michael May 19 '09 at 18:46
  • Okay, just tried it out, seems to work well even on DirectX apps. – Jan Gressmann May 19 '09 at 21:12
  • 3
    `if (GetWindowThreadProcessId(hwnd, &pid)` should read `if (GetWindowThreadProcessId(hwnd, &foregroundPid)`. As it is, you're comparing an uninitialized DWORD value to the PID of the foreground window. – Jeff May 04 '13 at 00:24