locked
get all form and this child controls RRS feed

  • Question

  • how to get all forms name and this child controls in my project in runtime?
    Monday, May 23, 2016 7:58 AM

Answers

All replies

  • Hi,

    do you want to get the open forms at runtime? You could use p/invoke calls to find windows but if your application needs to know open windows, then you should simply keep care of these:

    - You can add a static list of forms either globaly (e.g. static class or singleton pattern) or in each form you have.
    - Inside the constructor you add the form and you add an event listener to the Closed Event that will remove the instace again.

    This could be something like this:

    public partial class MyForm : Form
    {
            private static List<Form> _forms = new List<Form>();
    
            public MyForm()
            {
                InitializeComponent();
                _forms.Add(this);
                Closed += OnClosed;
            }
    
            public void OnClosed(object sender, EventArgs e)
            {
                _forms.Remove(this);
            }
    }

    (Just showing the main parts - you can build functions that access the _forms field of course!)

    The child controls can be accesses by the Controls Property of a form.

    With kind regards,

    Konrad

    Monday, May 23, 2016 8:21 AM
  • In order to get the displayed forms, try Application.OpenForms. Do you actually want to get all of the form classes?


    • Edited by Viorel_MVP Monday, May 23, 2016 9:10 AM
    Monday, May 23, 2016 9:09 AM
  • No dear

    i want get List of all forms in my project

     string ff = "";  
    Type formType = typeof(Form);
    foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
    
      if (formType.IsAssignableFrom(type))
    {
    ff += type.Name + "\n";
    }

    this code get all forms

    how to get this form child controls?

    Monday, May 23, 2016 9:23 AM
  • NOt open form

    get all form in project

    Monday, May 23, 2016 9:38 AM
  • Hi,

    you have to create an instance of the form to get all child controls.

    With kind regards,

    Konrad

    • Proposed as answer by Albert_Zhang Thursday, June 2, 2016 3:51 PM
    • Marked as answer by DotNet Wang Monday, June 6, 2016 2:54 AM
    Monday, May 23, 2016 9:51 AM
  • Expanding on Konrad's reply, you'll need to use Reflection to create an instance of each Form (and then iterate through the Form's this.Controls collection). See my blog post on the subject of how to use Reflection and a class I wrote to make it easier to use: http://geek-goddess-bonnie.blogspot.com/2009/09/reflection-in-net.html

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Proposed as answer by Albert_Zhang Thursday, June 2, 2016 3:51 PM
    • Marked as answer by DotNet Wang Monday, June 6, 2016 2:54 AM
    Tuesday, May 24, 2016 1:06 AM