You're going to run into a snag here because ToolStrip
uses Items
instead of Controls
, and ToolStripItem
does not inherit from Control
. Both ToolStripItem
and Control
inherit from Component
, so at best you can get an IEnumerable<Component>
.
You could accomplish this with the following extension method:
public static class ComponentExtensions
{
public static IEnumerable<Component> GetAllComponents(this Component component)
{
IEnumerable<Component> components;
if (component is ToolStrip) components = ((ToolStrip)component).Items.Cast<Component>();
else if (component is Control) components = ((Control)component).Controls.Cast<Component>();
else components = Enumerable.Empty<Component>(); // figure out what you want to do here
return components.Concat(components.SelectMany(x => x.GetAllComponents()));
}
}
On a Windows Form you could process all of these components in a foreach
loop:
foreach (Component component in this.GetAllComponents())
{
// Do something with component...
}
Unfortunately, you'll do a lot of manual type checking and casting.