TimUntersberger / nog

A tiling window manager for Windows
MIT License
697 stars 20 forks source link

Fix windows focusing when using the new keyboard hook funcitonality #292

Closed fredizzimo closed 3 years ago

fredizzimo commented 3 years ago

The new keyboard hook functionality did not work at all for me, on Windows 10, the windows focusing always failed with the message Failed to focus window in the log.

I'm not sure how it can work for others, but SetForegroundWindow has some very special requirements https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow. The most important one being that the calling process was the last one to receive the input event. Another one is the process being debugged, so perhaps you always run it through a debugger?

I don't believe that keyboard hooks ever count towards this requirement, but even if they did, the current code can potentially process the event before it returns 1 from the hook function, due to the usage of channels for the communication, so the ordering could be wrong.

The fix is pretty straightforward, just send a dummy input event before calling SetForegroundWindow, that fools Windows into thinking it received the last input. The workaround is pretty well known, and used in a few other similar Window managers. However this dummy event only works in Windows 10, and probably Windows 11, for earlier operating systems the alt key or similar would have to be used instead, see https://stackoverflow.com/questions/10740346/setforegroundwindow-only-working-while-visual-studio-is-open.

TimUntersberger commented 3 years ago

Whoops! Thank you!