Displaying a form from a dynamically loaded DLL

后端 未结 4 638
情深已故
情深已故 2020-12-29 11:14

This is an extension of a question I previously asked here.

Long story short, I dynamically load a DLL and make a type out of it with the following code:

相关标签:
4条回答
  • 2020-12-29 11:41

    Yes, you aren't actually specifying any code to run outside the class initializer. For instance, with forms you have to actually show them.

    You could modify your code to the following...

    Assembly assembly = Assembly.LoadFile("C:\\test.dll");
    Type type = assembly.GetType("test.dllTest");
    Form form = Activator.CreateInstance(type) as Form;
    form.ShowDialog();
    
    0 讨论(0)
  • 2020-12-29 11:41

    I would go with:

    Assembly assembly = Assembly.LoadFile("C:\\test.dll");
    Type type = assembly.GetType("test.dllTest");
    object obj = Activator.CreateInstance(type);
    Form form = obj as Form;
    if (form != null)
        form.Show(); //or ShowDilaog() whichever is needed
    

    Other error checking/handling should be added; however at the very least I would ensure the conversion works.

    0 讨论(0)
  • 2020-12-29 11:42

    If a class belongs to Form then the Assembly.GetType() returns NULL. If a class belongs to User Control then I can see that the type is returned.

    Also the syntax should be as:

    Type type = assembly.GetType("Assemblytest.clsTest");
    

    where

    • clsTest will be the name of class (of a user control)
    • Assemblytest is the name of assembly without the .dll extention.
    0 讨论(0)
  • 2020-12-29 11:45

    You have to do something with the form you've just created:

    Assembly assembly = Assembly.LoadFile("C:\\test.dll");
    Type type = assembly.GetType("test.dllTest");
    Form form = (Form)Activator.CreateInstance(type);
    form.ShowDialog(); // Or Application.Run(form)
    
    0 讨论(0)
提交回复
热议问题