How do I find out which control has focus in .NET Windows Forms?
Solution 1:
Form.ActiveControl
may be what you want.
Solution 2:
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
So use this (full disclosure: adapted from this C# answer)
Function FindFocussedControl(ByVal ctr As Control) As Control
Dim container As ContainerControl = TryCast(ctr, ContainerControl)
Do While (container IsNot Nothing)
ctr = container.ActiveControl
container = TryCast(ctr, ContainerControl)
Loop
Return ctr
End Function