c# - 从磁盘加载 WindowsFormsControlLibrary DLL,然后添加到控件,C#

标签 c# winforms

如何从磁盘加载 WindowsFormsControlLibrary UserControl,然后在运行时以编程方式将其添加到 Windows 窗体中的控件列表?

我只想从一个文件名开始。

下面的假代码说明了这一点。明确地说,我不想将它添加到 Visual Studio 工具箱并在设计时使用它。相反,我想在运行时加载它,并将它插入到 Windows 窗体中,除了文件名之外一无所知

    if (File.Exists("SomeUserControl.dll"))
    {
        // Load SomeUserControl.dll from disk
        // Do something to make it a control
        // ...
        UserControl SomeUserControl = new UserControl();
        Controls.Add(SomeUserControl);
    }

最佳答案

网上有很多例子和问题here on so .
一个非常简短的例子:

        // load your dll
        System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom("SomeUserControl.dll");

        // to get the right type use namespace.controlname
        Type type = assembly.GetType("MyControlLibrary.MyUserCtl");

        // create an instance
        object instanceOfMyType = Activator.CreateInstance(type);

        // do something with Control
        Control ctrl = instanceOfMyType as Control;
        if (ctrl != null)
        {
            this.Controls.Add(ctrl);
            ctrl.Dock = DockStyle.Bottom;
        }

并且不要忘记将其包装在 try/catch 中

关于c# - 从磁盘加载 WindowsFormsControlLibrary DLL,然后添加到控件,C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58417696/

相关文章:

c# - 求调用存储过程的合法例子 C# : MYSQL

c# - 与 List 相比,对对象使用 Custom Generic Collection 更快

c++ - 全屏形式和视频游戏有什么区别?

c# - 用户控件实例数的(合理)上限

c# - 从数据库流式传输数据 - ASP.NET Core & SqlDataReader.GetStream()

c# - 使用 Parallel.For 和 EPPlus 创建 Excel 工作表

c# - pinvoke - 传递一个字符串 [] 作为输出参数

c# - 如何检查一个url是否有子字符串

C# Windows 窗体应用程序无法从基于 Linux 的服务器正确读取文件

c# - 确定 DataGridView 中除新行之外的行数