Know who got the focus in a Lost Focus event

人走茶凉 提交于 2019-11-29 06:44:58
Vaccano

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

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.

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.

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

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!