.NET / Win32 - an event to detect when a window belonging to another application receives focus

I have a .NET application that should be able to detect when a particular window gains and loses focus. The special window that interests me relates to another application that I do not control, although I have a Window Handle.

I am really the best way to handle this. So far, I see two possibilities:

  • Using a Win32 timer call to monitor any status changes. It is small because it risks losing state changes, for example. if the window becomes active, then inactive during the timer interval
  • Using interceptors (SetWindowsHookEx) to intercept messages in a window. It seems like it should work, but it is worried that a) hooks at the global level will not work from .NET code, so they should be native and b) can this be considered virus / keylogger activity, so the OS is blocked ?

I am sure there are other options, if so, I would like to hear them!

+6
source share
2 answers

The easiest way is to use SetWinEventHook while listening to EVENT_SYSTEM_FOREGROUND events. You must use it with the WINEVENT_OUTOFCONTEXT flag to use it in .net: when using this flag, Windows sends notifications back to your own process, so you do not need a separate unmanaged DLL. However, note that the code calling this method must have a message loop.

A quick note on how this relates to the article mentioned in another answer: this article is about the SetWindowsHook API. SetWinEventHook is a separate API, but you use the same method to set up a P / Invoke call and to create a delegate for a callback - although note that both APIs use different parameters in both the API calls and the callbacks, The main advantage SetWinEventHook over SetWindowsHook is that for some types of hooks, SetWindowsHook requires the use of a separate unmanaged DLL, which you cannot do directly in .net. However, SetWinEventHook allows any type of callback, either using a separate unmanaged DLL, or notifying the source process without requiring a DLL, therefore more network-friendly.

+6
source

Here's an awesome article on using window hooks in .NET from MSDN magazine: Windows hooks in the .NET Framework .

As for your second concern, I have never heard of antiviruses detecting these api calls as spyware behavior.

Hope this helps!

0
source

Source: https://habr.com/ru/post/895614/


All Articles