Alex Rivera | Logout

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

Asked 2009-01-12T13:46:26.113
74

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

Edit
Report

2 Answers

27

After searching the Internet, I found the following on George Shepherd's Windows Forms FAQ

The .Net framework libraries does not provide you an API to query for the focused Control. You have to invoke a windows API to do so:

[C#]

public class MyForm : Form
{
          [DllImport("user32.dll", CharSet=CharSet.Auto, CallingConvention=CallingConvention.Winapi)]
          internal static extern IntPtr GetFocus();

          private Control GetFocusedControl()
          {
               Control focusedControl = null;
               // To get hold of the focused control:
               IntPtr focusedHandle = GetFocus();
               if(focusedHandle != IntPtr.Zero)
                    // Note that if the focused Control is not a .Net control, then this will return null.
                    focusedControl = Control.FromHandle(focusedHandle);
               return focusedControl;
          }
} 
answered 2009-01-12T14:07:18.410
2

If you follow ActiveControl out recursively it doesn't take you to the leaf control that has focus?

answered 2009-01-13T06:56:04.550

Your Answer