I'm trying to reliably detect when focus leaves a group of controls. So if I tab or click between two controls in the group, that's considered not leaving, but as soon as I click on a control outside the group, it raises an event. Here's how I'm currently doing it:
public class LeaveTracker
{
private HashSet<Control> trackedControls = new HashSet<Control>();
public void Track(Control ctrl)
{
ctrl.Leave += Ctrl_Leave;
trackedControls.Add(ctrl);
}
private void Ctrl_Leave(object sender, EventArgs e)
{
foreach (var ctrl in trackedControls)
if (ctrl.ContainsFocus)
return;
if (LeftControlGroup != null)
LeftControlGroup(this, EventArgs.Empty);
}
public event EventHandler LeftControlGroup;
}
Sometimes it works perfectly, but occasionally it seems to stop raising events. Is there a more reliable way to do this?