如何使用.NET Core的通用主机运行Win Forms并控制主机生命周期?

3

如何使用.NET Core的通用主机运行Win Forms并控制主机的生命周期?我想使用主机的默认构建器,并使用扩展方法添加我的启动窗体。我希望当启动窗体关闭时,主机也会关闭。

1个回答

8
你可以使用我编写的OswaldTechnologies.Extensions.Hosting.WindowsFormsLifetime库来实现此操作。
安装包:
Install-Package OswaldTechnologies.Extensions.Hosting.WindowsFormsLifetime

使用默认的.NET Core Win Forms模板之前的Program类:

static class Program
{
    /// <summary>
    ///  The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.SetHighDpiMode(HighDpiMode.SystemAware);
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

在安装包之后,将Program类转换为以下内容:
static class Program
{
    static void Main()
    {
        CreateHostBuilder().Build().Run();
    }

    public static IHostBuilder CreateHostBuilder() =>
        Host.CreateDefaultBuilder(Array.Empty<string>())
            .UseWindowsFormsLifetime<Form1>()
            .ConfigureServices((hostContext, services) =>
            {
                    
            });
}

您可以在Github仓库中查看代码:https://github.com/alex-oswald/WindowsFormsLifetime

编辑 2021-11-16 该库已更新为.NET 6。引入最小API后,使用通用主机启动Windows Forms应用程序只需4行!

var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsFormsLifetime<Form1>();
var app = builder.Build();
app.Run();


你为Application.xxx WinForms调用创建了自定义绑定,这些调用通常在调用Application.Run(Form)之前的代码中发生,但是如果我想在显示窗体之前进行自定义调用,例如连接到数据库,该怎么办? - user3625699
相关 GitHub 线程 - noseratio - open to work

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接