I have a .NET application that needs to be able to detect when a specific window gets and loses focus. The specific window i'm interested in belongs to another application that I have no control over, although I do have the Window Handle.
I'm really after the best way to tackle this. So far, I can see 2 possibilities:
I'm sure there are other options too, if so, i'd love to hear them!
Simplest way is likely to use SetWinEventHook, listening for EVENT_SYSTEM_FOREGROUND events. You need to use it with the WINEVENT_OUTOFCONTEXT flag to use it in .net: when you use this flag, Windows routes the notifications back to your own process, so you don't need a separate unmanaged DLL. Note however that the code that calls this method must have a message loop running.
Quick note on how this relates to the article mentioned in the other answer: that article focuses on the SetWindowsHook API. SetWinEventHook is a separate API, but you use the same technique to set up the P/Invoke call, and to set up a delegate for the callback - though note that the two APIs use different parameters in both the API calls themselves and in the callbacks. The main advantage that SetWinEventHook has over SetWindowsHook is that for some types of hooks, SetWindowsHook requires the use of a separate unmanaged DLL, which you can't do directly in .net. SetWinEventHook however allows either type of callback, using either a separate unmanaged DLL or notifying the original process without requiring a DLL, so is more .net-friendly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With