Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

OK, I get it: focus stealing is evil. Or at least it is 99.9% of the time. But I really need to steal the focus reliably on Windows 8, and so far I'm thwarted by the hordes of people insisting focus stealing is always evil.

Scenario: we run a custom application on an ordinary PC running Windows 8.1 (soon to be Windows 10). The screen, keyboard and mouse sit roughly 5m off the ground up some stairs that the forklift operator really shouldn't climb. The one input device they have is a numeric keypad on an extender cable down at their level. Everything they need to do they can do from that keypad... so long as some evil program hasn't stolen our application's focus, or some remote user hasn't logged out and left another application with focus.

The application is essentially a maximised desktop application - it fills the screen (but is not strictly a "full screen" or "topmost" application), and therefore allows other applications to appear in front of it when required. But when the mouse goes idle, we want this application to resume its "normal" position in front of all other applications so that it gets focus and the numeric keypad input will work reliably.

On Windows 7, using SetForegroundWindow() (enabled by AllowSetForegroundWindow() works fine - the application can be brought back to the front and resume focus. On Windows 8, SetForegroundWindow() only results in the taskbar icon flashing, but the application does not regain focus, forcing our user to climb the stairs... where the full keyboard and mouse is too tempting for them not to press buttons they shouldn't, and chaos typically ensues.

So please sir: can our (MFC, desktop) application steal back the focus once the mouse has gone idle for 1 minute, because it is more or less the only application that should normally be running anyway. If that is permitted, how do we steal it reliably?

like image 405
omatai Avatar asked Sep 11 '18 23:09

omatai


1 Answers

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.

like image 91
Daniel Sęk Avatar answered Nov 08 '22 14:11

Daniel Sęk