How to know which component is in focus?

2

I'm doing a form (Windows Forms) in C # and would like to know how do I get the component that is in focus. In my form there is a SplitterPanel and inside it, in Panel2 , has TabControl with several: ComboBox , TextBox and Button . I tried to use the ActiveControl property, but instead of picking up the component with focus, it gets SplitterPanel .

    
asked by anonymous 29.12.2014 / 14:21

2 answers

1

In this question in the OS I think you have the answer you want. Correct me if I'm wrong. You are right in your statement. I highlight the first two answers there.

A method that scans the controls to find which one is in focus (I created it as an extension method since it can be very useful for all controls):

public static Control FindFocusedControl(this Control control) {
    var container = control as IContainerControl;
    while (container != null) {
        control = container.ActiveControl;
        container = control as IContainerControl;
    }
    return control;
}

How to use:

formulario.ActiveControl.FindFocusedControl();

Or it has a form using the Win32 API:

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

      private Control GetFocusedControl() {
           Control focusedControl;
           // 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;
      }
}
    
29.12.2014 / 14:42
1

You can test whether the control returned by the ActiveControl property is a Container type control (that is, it implements the IContainerControl interface). If yes, you are looking for the ActiveControl container.

Here's an example I made in the MouseUp event of the form:

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
    var formSender = (Form)sender;

    var controle = formSender.ActiveControl;

    while (controle is IContainerControl)
    {
        var container = controle as IContainerControl;
        controle = container.ActiveControl;
    }

    MessageBox.Show(controle.Name);
}

Att.

    
29.12.2014 / 15:13