What is the preferred/easiest way to find the control that is currently receiving user (keyboard) input in WinForms?
So far I have come up with the following:
public static Control FindFocusedControl(Control control)
{
var container = control as ContainerControl;
return (null != container
? FindFocusedControl(container.ActiveControl)
: control);
}
From a form, this can be called simply as (in .NET 3.5+ this could even be defined as an extension method on the form) -
var focused = FindFocusedControl(this);
Is this appropriate?
Is there a built-in method that I should be using instead?
Note that a single call to ActiveControl is not enough when hierarchies are used. Imagine:
Form
TableLayoutPanel
FlowLayoutPanel
TextBox (focused)
(formInstance).ActiveControl will return reference to TableLayoutPanel, not the TextBox (because ActiveControl seems to only be returning immediate active child in the control tree, while I'm looking for the leaf control).
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…