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.
source share