You could even use WinEvents using SetWinEventHook. This might be less invasive than a global hook using SetWindowsHookEx. Once hooked you can listen for the EVENT_SYSTEM_FOREGROUND message.
SetWindowsHookEx