Is there an easy way to detect when a .NET app gets or loses focus?
6 Answers
The events you are looking for are Form.Activated and Form.Deactivated

- 6,580
- 2
- 25
- 33
-
thanks - that was my inclination, but i didn't know if it would work, since the app has a tabbed interface. i'll check into it. – subrama6 May 26 '09 at 15:30
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).

- 3,116
- 3
- 38
- 58
-
You could also filter your deactivate event by [detecting which application has focus][1] which you could put in the Deactivate handler for your main window, modal dialogues should return focus when exited. [1] http://stackoverflow.com/questions/2183541/c-detecting-which-application-has-focus – Dead.Rabit Nov 19 '12 at 17:49
Use:
this.LostFocus
And:
this.GotFocus
On the most-parent form/window

- 28,099
- 24
- 107
- 147
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.

- 3,304
- 1
- 26
- 32
Handle the Control.GotFocus and Control.LostFocus events for the main window.

- 58,735
- 39
- 131
- 204