Is there an easy way to detect when a .NET app gets or loses focus?
For WPF, FocusChanged on the window. There should be a similar event in Winforms. You can find out using the intellisense on Visual Studio.
Activated/Deactivated seems to be standard though.
Handle the Control.GotFocus and Control.LostFocus events for the main window.
Use:
this.LostFocus
And:
this.GotFocus
On the most-parent form/window
The events you are looking for are Form.Activated and Form.Deactivated
I was curious how this technique would work under the various conditions within an MDI app. It turns out that this won't work in all situations.
If you application is an MDI app, then the main MDI form will lose/get focus if a non-modal form within the MDI form has focus when the app itself loses/regains focus (as noted in other answers). However, if a modal dialog is open (modal to the app itself), the main MDI form doesn't loose/gain focus (at least the activated/deactivated events don't seem to fire). In other words if all you handle is the MDI form's activate/deactivated events, you could miss when the app looses/gains focus if a modal form has focus.
Thus it seems that for this to work, you'll need to handle both the activated/deactivated events of the MDI form and also those events on any form opened modally (via ShowDialog).