Find components on a windows form c# (not controls)

后端 未结 2 925
攒了一身酷
攒了一身酷 2020-12-17 14:53

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         


        
相关标签:
2条回答
  • 2020-12-17 15:38

    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>();
            }
        }
    
    0 讨论(0)
  • 2020-12-17 15:53

    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;
    }
    
    0 讨论(0)
提交回复
热议问题