I’ve recently needed to find what control currently has focus in my WinForms application. Google gave me two answers. The first depends on unmanaged code, and the second is fully managed.
Reference
[csharp]
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr GetFocus();
private Control GetFocusedControl()
{
Control ctl = FromHandle(CreateProjectPanel.GetFocus());
//MessageBox.Show(ctl.Name);
return ctl;
}
[/csharp]
I can’t remember where I found this second solution, but it is the one I use in my code. It uses the Control.Focused and Control.ContainsFocus properties to recursively find the focused control.
[csharp]
private System.Windows.Forms.Control GetFocusedControl(System.Windows.Forms.Control.ControlCollection Controls)
{
// store focused control…
foreach (System.Windows.Forms.Control clsControl in Controls)
{
if (clsControl.Focused)
{
return clsControl;
}
if (clsControl.ContainsFocus)
{
if (clsControl.Controls.Count == 0)
{
return clsControl;
}
else
{
return GetFocusedControl(clsControl.Controls);
}
}
}
// no focus…
return null;
}
// usage
Control hasFocus = GetFocusedControl(this.FindForm().Controls);
[/csharp]