2

I'm trying to figure out why these two lines of code sometimes return different values:

var focus = FindFocusedControl(_targetForm).Name;
var active = _targetForm.ActiveControl.Name;

FindFocusedControl comes from here:

private static Control FindFocusedControl(Control control)
{
    var container = control as ContainerControl;
    while (container != null)
    {
        control = container.ActiveControl;
        container = control as ContainerControl;
    }
    return control;
}

Is my active simply the one least able to be drilled down into? Does it depend on whether the control that actually has focus is inside a UserControl?

Community
  • 1
  • 1
Bobson
  • 13,498
  • 5
  • 55
  • 80
  • Maybe this helps: http://stackoverflow.com/q/802722 – Ahmet Kakıcı Dec 30 '13 at 20:55
  • @AhmetKakıcı - I found that, but no, it doesn't explain the difference in a way I can understand. I get that `Focus()` is lower level, but that doesn't explain why they're *different*. – Bobson Dec 30 '13 at 20:56
  • FindFocusedControl just has a bad name, it doesn't actually find the control with the focus. Try it on a button inside a panel inside a panel, it returns the panel instead of the button. Just get rid of it. – Hans Passant Dec 30 '13 at 21:14
  • @HansPassant - That scenario works just fine for me. In fact, they return the same thing in that case. – Bobson Dec 30 '13 at 21:21
  • That's not possible with two panels and one button. ContainerControl.ActiveControl also tracks controls that can never get the focus. The active control for the outer panel is the inner panel. – Hans Passant Dec 30 '13 at 21:24
  • @HansPassant - But I never return the outer panel's `ActiveControl`. I'm either asking the `Form` as a whole or I'm seeing that the outer panel has an active inner panel and iterating into that, which gives me the button. So the fact the inner panel can't get focus on its own doesn't matter. – Bobson Dec 30 '13 at 21:31

1 Answers1

2

_targetForm.ActiveControl will return the control on the form that either has the focus or one of its child controls has the focus.

Your FindFocusedControl implementation does the same, but recursively checks the child controls until it reaches the control that has focus, and returns that.

So for controls directly on the form, they will return the same value, but for controls stacked on panels or other containers, the returned values will be different.

Louis Somers
  • 2,560
  • 3
  • 27
  • 57
  • That makes a lot of sense. I've long since lost access to the code base that this was part of, but this sounds very plausible, so I'll accept it. – Bobson Dec 17 '18 at 18:22