2

I have a WinForms project, using Visual Studio 2013, DotNet Framework 4.0. How can I get a list of all of my created Forms and User Controls in the project, preferably at runtime?

EDIT: Thanks for your reply. SO for example, I want to get the FOrms and User Controls under the namespace "MyApp.Forms" and "MyApp.UserControls", how can I get the assemblies? Here's how I do it:

IEnumerable<Assembly> CurrentDomainAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.StartsWith("MyAppNamespace"));
        foreach (Assembly a in CurrentDomainAssemblies)
        {
            IEnumerable<Type> AssembliesTypes = a.GetTypes().Where(t => (typeof(Form).IsAssignableFrom(t) || typeof(UserControl).IsAssignableFrom(t)) && t.IsClass);
            foreach (Type t in AssembliesTypes)
            {
                if (t.FullName.Contains("Usercontrol"))
                {
                    listUc.BeginUpdate();
                    listUc.Items.Add(t.Name);
                    listUc.EndUpdate();
                }
                if (t.FullName.Contains("Forms"))
                {
                    listForm.BeginUpdate();
                    listForm.Items.Add(t.Name);
                    listForm.EndUpdate();
                }

EDIT: This approach based on the namespace of Forms and User Controls. Is it posssible to get its filename, not its namespace?

Harry
  • 678
  • 10
  • 26

1 Answers1

4

If you want to see all the classes(Forms or UserControls) you can use Reflection. But there is no such thing like project during runtime. You can get the list based on the assembly.

EDIT: Try this

foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies().Where(a=>!a.FullName.StartsWith("System.") || !a.FullName.StartsWith("Microsoft.")))
            {
                var types = a.GetTypes().Where(t => (typeof(Form).IsAssignableFrom(t) || typeof(UserControl).IsAssignableFrom(t) )&& t.IsClass && t.FullName.StartsWith("YourNamespace."));


            }
Rishikesh
  • 486
  • 6
  • 15
  • I'm having problem getting assembly information, please see my updated question. – Harry Apr 22 '14 at 02:14
  • Thank you, I have modified your code for better performance. I have another problem: Is it possible to get each Forms and UserControls filename, not namespace? – Harry Apr 22 '14 at 09:52