6
votes

I have a User Control that has several children elements, including checkboxes and textboxes.

I would like to trigger the LostFocus event for my User Control only when the focus is lost on the entire User Control (e.g. clicking a button outside of the User Control).

Currently, the LostFocus event is also triggering when I move between children elements of my User Control, e.g. from one textbox to another.

1

1 Answers

-1
votes
protected override void OnLostFocus(EventArgs args)
{
      if (!ContainsFocus)
      {
          // Only do something here
      }
}

The trick is to check for ContainsFocus

In your constructor you'll probably will have to add code similar to the following to capture the lost focus of your child controls (as you won't get direct notification when they lose focus to somewhere else) by calling

CaptureLostFocus(this);

and implementing:

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