Prevent LostFocus from starting when elements lose focus

I have a user control that contains several child elements, including checkboxes and text fields.

I would like to fire the LostFocus event for my User Control only when the focus is lost on the entire user control (for example, by clicking a button outside the user control).

Currently, the LostFocus event is also fired when I move between the children of my User Control, for example. from one text box to another.

+6
source share
1 answer
protected override void OnLostFocus(EventArgs args) { if (!ContainsFocus) { // Only do something here } } 

The trick is to check ContainsFocus

In your constructor, you may have to add code similar to the following to capture the lost focus of your child controls (since you will not receive direct notification when they lose focus elsewhere), causing

 CaptureLostFocus(this); 

and implementations:

 void CaptureLostFocus(Control control) { foreach(Control child in control.Controls) { child.LostFocus += (s, e) => OnLostFocus(e); CaptureLostFocus(control); } } 
-1
source

All Articles