Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

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

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<Control> AllControls)
{
    String controlName = "";
    controlName = control.Name;

    foreach (Control c in control.Controls)
    {
        controlName = c.Name;
        if ((control.Controls.Count > 0))
        {
            AllControls.Add(c);
            FillControls(c, AllControls);
        }
    }
}

However this function does not retrieve the non-visual components on the bottom of the form like the HelpProvider, ImageList, TableAdapters, DataSets, etc.

Is there a way to get the list of these components as well?

Edit:

Thanks @HighCore for pointing me to use System.ComponentModel.Component instead in a similar function does get me a list with components such the ImageList, the Help Provider and the BindingSource. However, I still miss from this list the TableAdapters and the DataSets. I suppose because those inherit directly from Object.

Please. Don't refer me to older posts which shows a similar function to mine and that only gets the list of the controls.

Edit: Why the negative votes? This question has never been answered before!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...