Vaccano
Vaccano

Reputation: 82341

Know who got the focus in a Lost Focus event

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.

Upvotes: 9

Views: 12178

Answers (5)

Marcelo Camargo
Marcelo Camargo

Reputation: 2298

This is a shorter code for the Vaccano's answer, using Linq

private static Control FindFocusedControl(Control container)
{
    foreach (Control childControl in container.Controls.Cast<Control>().Where(childControl => childControl.Focused)) return childControl;
    return (from Control childControl in container.Controls select FindFocusedControl(childControl)).FirstOrDefault(maybeFocusedControl => maybeFocusedControl != null);
}

Exactly the same (in high-level, abstraction).

Upvotes: 1

Vaccano
Vaccano

Reputation: 82341

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!
}

Upvotes: 6

OlimilOops
OlimilOops

Reputation: 6797

No. first comes the LostFocus-event of one control then comes the GotFocus-event of the next control. as long as you can not figure out which control the user uses in the next moment, it is not possible.
whereas if the compact framework control does have a TabIndex-property it could be predicted only if the user uses the tab-key.

Edit: OK You posted the solution and it works fine I must admit: the simple "No" is wrong +1

Upvotes: 1

dretzlaff17
dretzlaff17

Reputation: 1719

Using the corell.dll looks like a good idea.

Another possible way is to create GotFocus event handlers for all the controls on your form Then create a class level variable that updates with the name of the control that has the current focus.

Upvotes: 1

Chris Taylor
Chris Taylor

Reputation: 53699

One option would be to interop the GetFocus API

[DllImport("coredll.dll, EntryPoint="GetFocus")]
public extern static IntPtr GetFocus();

This will give you the handle to the window that currently has input focus, you can then recursively iterate the control tree to find the control with that handle.

Upvotes: 2

Related Questions