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