尝试使用在控制台应用程序的运行时导入的DLL显示Windows窗体 [英] Trying to show a Windows Form using a DLL that is imported at the runtime in a console application

查看:343
本文介绍了尝试使用在控制台应用程序的运行时导入的DLL显示Windows窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一些研究项目,这个迷你项目是其中的一部分。这个迷你项目的目的是在运行时导入DLL,并加载存储在该DLL中的GUI。我试图从DLL的函数中触发Windows窗体的 Show()函数。代码如下所示:
控制台应用程序代码

I am working on some research project and this mini project is a part of it. The objective of this mini project is to import the DLL at runtime and load the GUI stored in that DLL. I am trying to fire Show() function of Windows Form from a function of the DLL. Here's how the code looks like: Console Application Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace DLLTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string DLLPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\TestLib.dll";
            var DLL = Assembly.LoadFile(DLLPath);

            foreach (Type type in DLL.GetExportedTypes())
            {
                dynamic c = Activator.CreateInstance(type);
                c.test();
            }

            Console.ReadLine();
        }
    }
}

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestLib
{
    public class Test
    {
        public int test()
        {
            Form1 form = new Form1();
            form.Show();
            return 0;
        }
    }
}

函数<$ c $当我返回一些值并显示在控制台应用程序时,c> test()正常工作。但是,当我尝试显示表单时,它显示了这个例外:

The function test() is working fine when I just return some value and show on the console application. But, when I try to show the form, its showing me this exception:


'TestLib.Form1'不包含'测试'

'TestLib.Form1' does not contain a definition for 'test'

请告诉我如何解决这个问题?

Please tell me how can I solve this?

推荐答案

问题是 Activator.CreateInstance 不返回ExpandObject(动态)。
您应该通过反射运行test(),如下所示:

The problem is that Activator.CreateInstance does not return ExpandObject (dynamic). You should run test() by reflection, like this :

    foreach (Type type in DLL.GetExportedTypes())
    {
        dynamic c = Activator.CreateInstance(type);
        MethodInfo methodInfo = type.GetMethod("test");
         methodInfo.Invoke(c , null);
    }

这篇关于尝试使用在控制台应用程序的运行时导入的DLL显示Windows窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆