lundi 11 septembre 2017

How to call WinForm Show() method using reflection

I have the following class (exposed to COM) which I am using as a wrapper to show forms called from VB6.

public class NetForm : INetForm
{
    public NetForm(Assembly assembly, string name, object[] parameters)
    {
        Assembly = assembly;
        Name = name;
        CreateInstance(parameters);
    }

    private Assembly Assembly { get; set; }
    private string Name { get; set; }
    private Form Instance { get; set; }

    private void CreateInstance(object[] parameters)
    {
        Type type = Assembly.GetType(Name);
        Type[] types = new Type[parameters.Length];
        for (int idx = 0; idx < parameters.Length; idx++)
            types[idx] = parameters[idx].GetType();

        ConstructorInfo ci = type.GetConstructor(types);
        Instance = (Form)ci.Invoke(parameters);
    }
    public void Show()
    {
        Instance.Visible = true;
        Instance.Show();       // Crashing
    }
    public void ShowDialog()
    {
        Instance.ShowDialog();  // Works perfectly
    }
}

public class NetAssembly
{
    public NetAssembly(string fullname)
    {
        Init(fullname);
    }

    private Assembly Assembly { get; set; }

    private void Init(string name)
    {
        Assembly = Assembly.LoadFrom(name);            
    }

    public NetForm GetForm(string nameSpace, string name, object[] parameters)
    {
        name = string.Concat(nameSpace, ".", name);
        return new NetForm(Assembly, name,parameters);
    }
}

  1. ShowDialog() works perfectly.
  2. Show() is not being displayed if the Visible property is not set to True. But also when setting it to true, the form is partially being displayed and crash after few seconds.

I am using a UnitTestProject to check it:

[TestClass]
public class NetFormUnitTest
{
    [TestMethod]
    public void ShowTestMethod()
    {
        var assembly = new NetAssembly(assemblyFullName);
        var form = assembly.GetForm(nameSpace, formName, new object[] { "Item1" });
        form.Show();
    }
}

What is the correct way to call the Show() method?





Aucun commentaire:

Enregistrer un commentaire