C# exe窗体项目改dll并调用

发布于:2025-03-30 ⋅ 阅读:(26) ⋅ 点赞:(0)

将Windows Forms EXE项目转换为DLL项目的步骤如下:

1.修改项目属性:

右键项目 > 属性 > 应用程序
将"输出类型"从Windows应用程序改为类库

2. 移除入口点:

打开Program.cs,注释并增加以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestTool
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        //[STAThread]
        //static void Main()
        //{
        //    Application.EnableVisualStyles();
        //    Application.SetCompatibleTextRenderingDefault(false);
        //    Application.Run(new Form1());
        //}
    }

    public static class FormHelper
    {
        public static void ShowMainForm()
        {
            Application.Run(new Form1());
        }
    }
}

3. 调整窗体访问修饰符

public partial class Form1 : Form // 从internal改为public
{
    public Form1()
    {
        InitializeComponent();
    }
}

在其他项目中调用

复制test.dll到新项目下

在其他项目中调用

添加DLL引用:
右键调用项目 > 添加 > 引用
浏览找到你的DLL文件并添加

创建STA线程调用:

private void button1_Click(object sender, EventArgs e)
{

    // 创建专用STA线程
    Thread staThread = new Thread(() =>
    {
        try
        {
            // 初始化工具窗体
            TestTool.FormHelper.ShowMainForm();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"错误:{ex.Message}");
        }
    });

    staThread.SetApartmentState(ApartmentState.STA);
    staThread.Start();
}