views:

625

answers:

6

Is there an easy way to detect when a .NET app gets or loses focus?

A: 

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.

apandit
A: 

In winforms it's Activated

Chris S
A: 

Handle the Control.GotFocus and Control.LostFocus events for the main window.

Scott Langham
+1  A: 

Use:

this.LostFocus

And:

this.GotFocus

On the most-parent form/window

joshcomley
+3  A: 

The events you are looking for are Form.Activated and Form.Deactivated

Jeremy
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
A: 

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).

Greg McGuffey