mercredi 7 mars 2018

Execute all methods in multiply forms WinForm application with reflection

In testing purposes I have to start certain methods of app during the runtime. The app consists out of 3 Forms, ParentForm and 2 child forms, Form1 and Form2. With reflection and some threading manipulation I start the ParentForm.

var assembly = Assembly.LoadFrom(@"E:\ReflectionTestApp\bin\Debug\ReflectionTestApp.exe");

var oh = ShowForm(assembly.Location, "ReflectionTestApp.ParentForm");

private static ObjectHandle ShowForm(string executable, string type)
{
    ObjectHandle oh = null;
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    var t = new Thread(() =>
    {                            
        oh = Activator.CreateInstanceFrom(executable, type);
        Application.Run((Form)oh.Unwrap());
    });
    t.Start();
    while (t.ThreadState != ThreadState.Running || oh == null);
}

Further to get the controls of certain method to get required method.

 var setLabelOneMethod = assembly.GetType("ReflectionTestApp.Form1")
                                .GetMethods(BindingFlags.Public | BindingFlags.NonPublic |
                                                  BindingFlags.Static | BindingFlags.Instance)
                                .Single(m => m.Name == "setLabelOne");

So i can get all methods from all available forms but to execute required method i should Unwrap the form, if the form differs from the started form, app throws Null reference exception. Or if the form method has some dependencies to another form the unwrapped form will have own instance which differs from main app instance.

var form = (Form)oh.Unwrap();

Is it possible in Reflection to get the Instance of whole app and not only started Form and on demand execute required methods?

Please be polite, I'm new in this topic, I don't need implementation but any advice or possible direction or literature link would be nice.





Aucun commentaire:

Enregistrer un commentaire