如何在.NET Core3.1 类库项目中使用System.Windows.Forms

网上说法大多都是直接添加对.Net Framework框架的引用,但是这种方法打包很不友好。于是开始了网络搜索,翻到了微软的文档,才找到直接引用 System.Windows.Froms 程序集的方法。还隐藏的很深,地址:Upgrade a Windows Forms app to .NET 7 - Windows Forms .NET | Microsoft Learn

很明显没有这个System.Windows.Forms程序集,要求 .Net Core 版本 >= 3.0,其实只要修改项目的csproj文件就好了:

可以使用记事本或在项目上直接左键双击:

初始化文件内容大致如下:

修改第一行的SDK,注意多的这个WindowsDesktop

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

修改PropertyGroup:

<PropertyGroup>

<TargetFramework>netcoreapp3.1</TargetFramework>

<OutputType>Library</OutputType>

<UseWindowsForms>true</UseWindowsForms>

</PropertyGroup>

在.NET Core 3.1中使用WPF或Winforms的示例:需要添加UseWPF和UseWindowsForms标记:

<UseWPF>true</UseWPF>

<UseWindowsForms>true</UseWindowsForms>

修改完成之后,代码显示即正常了:

生成项目也是成功的:

如果使用net6.0的话,可以直接写 <TargetFramework>net6.0-windows</TargetFramework> 即可。

针对.NET Core < 3,它在Windows上没有WinForms,但是,如果您需要在Linux上使用WinForms进行编译,则仍然有效,因为.NET Core WinForms仅在Windows上运行。

混合框架当然是解决问题的一种方法-但是,为什么要使用.NET Core?

但是您可以做的是将System.Windows.Forms的单声道实现移植到NetStandard。

如这里:https://github.com/ststeiger/System.CoreFX.Forms

希望本文对你有帮助。

相关推荐
驾驭人生20 小时前
Asp .Net Core 系列:Asp .Net Core 集成 Hangfire+MySQL
数据库·mysql·.netcore
时光追逐者20 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 53 期(2025年9.1-9.7)
c#·.net·.netcore
somethingGoWay2 天前
wpf .netcore 导出docx文件
wpf·.netcore
somethingGoWay2 天前
wpf .netcore 导出pdf文件
pdf·wpf·.netcore
切糕师学AI3 天前
如何建立针对 .NET Core web 程序的线程池的长期监控
java·前端·.netcore
almighty273 天前
C# WinForm分页控件实现与使用详解
c#·winform·分页控件·c#分页·winform分页
csdn_aspnet4 天前
使用 MongoDB.Driver 在 C# .NETCore 中实现 Mongo DB 过滤器
mongodb·c#·.netcore
tiancao2224 天前
安装3DS MAX 2026后,无法运行,提示缺少.net core的解决方案
.net·.netcore·3dsmax
csdn_aspnet4 天前
使用 C# .NETCore 实现MongoDB
mongodb·c#·.netcore
MoFe18 天前
【.net core】【NPOI】读取表格信息(处理合并行表格数据)
.netcore