Know who got the focus in a Lost Focus event

末鹿安然 提交于 2019-11-30 08:25:10

问题


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.


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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




回答5:


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



来源:https://stackoverflow.com/questions/2899338/know-who-got-the-focus-in-a-lost-focus-event

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