0

I have a SplitContainer. On both Panels there are some controls filling them. I would like to determine which Panel is holding acutally focused control. I mean when control got focus - I want to know that e.g. Panel1 got focused. Is that possible to achieve without passing event?

Edit: I need it to work with nested controls to.

Joe
  • 2,551
  • 6
  • 38
  • 60

1 Answers1

1

You can use this code. It returns the first panel with a focused control. Doesn't work for nested controls (i.e. a TextBox in a Panel in a SplitterPanel).

var panels = splitContainer1.Controls.OfType<SplitterPanel>();
var focusedPanel = panels.FirstOrDefault(p => p.Controls.OfType<Control>().
                          Any(c => c.Focused));

EDIT: To support recursive children detection, you can use this method:

static IEnumerable<Control> GetNestedChildren(Control container)
{
    var children = container.Controls.OfType<Control>().ToArray();
    return children.Concat(children.SelectMany(GetNestedChildren));
}

And your former code would become:

var panels = splitContainer1.Controls.OfType<SplitterPanel>();
var focusedPanel = panels.
    FirstOrDefault(p => GetNestedChildren(p).
        Any(c => c.Focused));
e_ne
  • 8,340
  • 32
  • 43
  • That is a nice solution but I need it for nested controls to. If no solution will appear I will mark this as the closest to what I need. – Joe Dec 19 '12 at 07:19
  • That is really nice. The only thing is that it would have to be fired by global app click event I guess, so every click would implicate iteration through all SplitterPanel's children. But it's still pretty nice solution. Thanky you. – Joe Dec 20 '12 at 07:53