Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find out which control has focus in .NET Windows Forms?

Tags:

How do I find out which control has focus in Windows Forms?

like image 952
Jeff Avatar asked Mar 18 '09 21:03

Jeff


People also ask

What are the controls of Windows form?

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.

Which method is used to set input focus to the control?

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.

What does focus () do in C#?

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.


2 Answers

Form.ActiveControl may be what you want.

like image 50
Ken Browning Avatar answered Sep 23 '22 05:09

Ken Browning


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 
like image 41
MarkJ Avatar answered Sep 21 '22 05:09

MarkJ