Displaying a form from a dynamically loaded DLL

2019-02-03 11:20发布

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:

Assembly assembly = Assembly.LoadFile("C:\\test.dll");
Type type = assembly.GetType("test.dllTest");
Activator.CreateInstance(type);

From there I can use type to reference virtually anything in the dllTest class. The class by default when ran should bring up a form (in this case, fairly blank, so it's not complex).

I feel like I'm missing a key line of code here that's keeping the form from loading on the screen.

dllTest.cs (within the DLL) consists of:

namespace test
{
    public partial class dllTest : Form
    {
        public dllTest()
        {
            InitializeComponent();
        }
    }
}

InitializeComponent() sets up the layout of the form, which is far too long to paste here and shouldn't make a difference.

Any ideas?

标签: c# dll forms
4条回答
放我归山
2楼-- · 2019-02-03 11:40

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.

查看更多
地球回转人心会变
3楼-- · 2019-02-03 11:41

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)
查看更多
Melony?
4楼-- · 2019-02-03 11:43

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();
查看更多
叼着烟拽天下
5楼-- · 2019-02-03 11:57

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.
查看更多
登录 后发表回答