.NET/Win32 - event to detect when a window belonging to another app gets focus

后端 未结 2 1809
醉梦人生
醉梦人生 2020-12-31 23:32

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

相关标签:
2条回答
  • 2021-01-01 00:21

    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.

    0 讨论(0)
  • 2021-01-01 00:31

    Here's an awesome article about implementing windows hooks in .NET from the MSDN magazine: Windows Hooks in the .NET Framework.

    As for your second concern, I've never heard about antiviruses detecting these api calls as spyware behavior.

    Hope it helps!

    0 讨论(0)
提交回复
热议问题