Know who got the focus in a Lost Focus event

Vaccano picture Vaccano · May 24, 2010 · Viewed 12k times · Source

Is it possible to know who got the focus in a lost focus event?

Compact Framework does not have an ActiveControl, so I don't know how to tell who got the focus.

Answer

Vaccano picture Vaccano · May 25, 2010

This is the solution that ended up working:

public System.Windows.Forms.Control FindFocusedControl()
{
    return FindFocusedControl(this);
}

public static System.Windows.Forms.Control FindFocusedControl(System.Windows.Forms.Control container)
{
    foreach (System.Windows.Forms.Control childControl in container.Controls)
    {
        if (childControl.Focused)
        {
            return childControl;
        }
    }

    foreach (System.Windows.Forms.Control childControl in container.Controls)
    {
        System.Windows.Forms.Control maybeFocusedControl = FindFocusedControl(childControl);
        if (maybeFocusedControl != null)
        {
            return maybeFocusedControl;
        }
    }

    return null; // Couldn't find any, darn!
}