How do I find out which control has focus in Windows Forms?
Windows Forms controls are reusable components that encapsulate user interface functionality and are used in client-side, Windows-based applications. Not only does Windows Forms provide many ready-to-use controls, it also provides the infrastructure for developing your own controls.
Use the SetFocus method when you want a particular field or control to have the focus so that all user input is directed to this object. To read some of the properties of a control, you need to ensure that the control has the focus.
The Focus method attempts to give the specified element keyboard focus. The returned element is the element that has keyboard focus, which might be a different element than requested if either the old or new focus object block the request.
Form.ActiveControl
may be what you want.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With