Know who got the focus in a Lost Focus event
Is it possible to know who got the focus in a lost focus e开发者_如何学编程vent?
Compact Framework does not have an ActiveControl
, so I don't know how to tell who got the focus.
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).
精彩评论