How to reliably steal/regain focus for MFC/desktop app on Windows 8.1/10? How to reliably steal/regain focus for MFC/desktop app on Windows 8.1/10? windows windows

How to reliably steal/regain focus for MFC/desktop app on Windows 8.1/10?


Configure hotkeys on numeric keypad (RegisterHotKey).

Pressing a registered hotkey gives you the foreground activation love by Raymond Chen

After you call the RegisterHotKey function to register a hotkey, the window manager will send you a WM_HOTKEY message when the user presses that hotkey, and along with it, you will get the foreground love. If you call SetForegroundWindow from inside your hotkey handler, the foreground window will change according to your instructions.


Possible solution (with major limitations): do nothing extra; wait.

One of our service technicians observed that on the third or fourth attempt to regain focus using AllowSetForegroundWindow() and SetForegroundWindow() as had been working on Windows 7, Windows 8 finally allowed our application to regain focus. It is not clear what the conditions are that make this work, or if it works reliably, but we have now observed our application regaining focus from beneath Chrome, from beneath another (self-developed) MFC application, and from beneath a third party application - all desktop applications. Approximately 3-4 minutes needed to elapse in each case before focus was surrendered back to our (desktop) application.

However, we have not witnessed it regain focus from beneath metro applications, and nor do we expect it (e.g. hit the Windows key and leave the system lingering on the Start screen).

In our (restricted) situation, we are willing to take the gamble that our users will not launch a metro application that obscures our desktop application, at least not without restoring our application, since their business relies on it. Our main concern is that one of our busy service technicians will log in remotely, get distracted, and carelessly leave one of our desktop utilities with the focus. Waiting 3-4 minutes appears to be a solution to this specific scenario.


I would try it in this way:

  1. Setup a timer in you application. That checks GetForegroundWindow on a regular basis.
  2. If GetForgroundWindow does not belong to your process (GetWindowThreadProcessId)
  3. If a different process onws the foreground window use AttachThreadInput and attach your input queue to the input queue of the other process.
  4. Now use SetForegoundWindow and detach the thread input again.
  5. Now you can use SetFocus as needed to control the input focus of your program.