Is there a way to be notified of when focus changes from any window to another window(even between windows applications) such that I can just have my delegate called immediately when the user changes focus??
I keep thinking I may just have to do polling 🙁 🙁 every 1 second and call GetForegroundWindow but I really don’t want to do that.
SetWinEventHook() is probably your best bet; you can listen to either the EVENT_SYSTEM_FOREGROUND to listen for foreground window changes – or even EVENT_OBJECT_FOCUS to listen for more fine-grain focus changes within apps and within controls.
You’ll need to use this with the WINEVENT_OUTOFCONTEXT flag; this means that the change notification will be delivered asynchronously to your own app, so you won’t need a separate DLL – you’ll still need to P/Invoke though. But the notification won’t be instant – there may be a small delay – but that’s implied with asynchronous. If you want to do something absolutely immediately with no delay whatsoever, you’re going to need to use C++ and an in-process hook (either SetWinEventHook with WINEVENT_INCONTEXT or the SetSetWindowsHookEx-style hook.)
Here’s a sample that seems to do what you’re looking for: