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

前端 未结 1 663
日久生厌
日久生厌 2020-12-19 09:30

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

相关标签:
1条回答
  • 2020-12-19 09:49

    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.

    0 讨论(0)
提交回复
热议问题