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

元气小坏坏 提交于 2019-12-05 06:24:09

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.

xMRi

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!