In this question in the OS I think you have the answer you want. Correct me if I’m wrong. You’re right in your statement. I highlight the first two answers there.
Method that scans the controls to find which one is in focus (I created as extension method since it can be quite 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;
}
I put in the Github for future reference.
Way to use:
formulario.ActiveControl.FindFocusedControl();
Or have a shape 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;
}
}
I put in the Github for future reference.
I had found a code similar to the first example, but it ran through all the components (I didn’t think this was cool), but the one that you went through, it only goes through the hierarchy until you get to the component with the focus, so I tested
FindFocusedControl
was faster thanGetFocusedControl
(usedStopwatch
to test). Note: the extension really simplifies things, but it is in trouble and is not working– mateusalxd
What problems?
– Maniero
container
undefined in context;control = container.ActiveControl;
makes an error whencontainer
is void; lack of;
at the end of the line ofwhile
... are simple things, only it would be good to leave the correct answer!– mateusalxd
Look now. It was just a lack of attention in the rush.
– Maniero
errors still continue, if you put the code of your first answer and only do it as an extension, it works perfectly!
– mateusalxd
I think now I found the problem. Is that I don’t have Visual Studio to test.
– Maniero
understood, the error still continues, the problem occurring on this line
control = container.ActiveControl;
, because in the last iteration thecontainer
is null, I can adjust or you better arrange it yourself?– mateusalxd
If you can do it, you can do it.
– Maniero