Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way to find focused control in WinForms app?

Tags:

.net

winforms

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).

like image 247
Milan Gardian Avatar asked Jan 12 '09 13:01

Milan Gardian


People also ask

What is focus method 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.

What Windows form controls?

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.

When a control has focus it can accept?

A control can be selected and receive input focus if all the following are true: the Selectable value of ControlStyles is set to true , it is contained in another control, and all its parent controls are both visible and enabled.


1 Answers

If you have other calls to the Windows API already, there's no harm in using Peters solution. But I understand your worries about it and would tend to a similar solution as yours, using only the Framework functionalities. After all, the performance difference (if there is one) shouldn't be significant.

I would take a non recursive approach:

public static Control FindFocusedControl(Control control) {     var container = control as IContainerControl;     while (container != null)     {         control = container.ActiveControl;         container = control as IContainerControl;     }     return control; } 
like image 55
Hinek Avatar answered Sep 24 '22 20:09

Hinek