I know how to find and collect a list of all the controls used in a Windows Form. Something like this:
static public void FillControls(Control control, List
All controls built through the designer must have a private field called "components" of type IContainer. You can use reflection to get the value of this field, if it exists, and then iterate through the components.
This method differs from the other answer in that this will only return the components added to the form using the designer, as opposed to all fields that can be cast as Component.
public IEnumerable<Component> GetComponents(Control c)
{
FieldInfo fi = c.GetType()
.GetField("components", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (fi?.GetValue(c) is IContainer container)
{
return container.Components.OfType<Component>();
}
else
{
return Enumerable.Empty<Component>();
}
}
Surprisingly, it seems the only way to do this is via reflection.
private IEnumerable<Component> EnumerateComponents()
{
return from field in GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
where typeof (Component).IsAssignableFrom(field.FieldType)
let component = (Component) field.GetValue(this)
where component != null
select component;
}