如何在.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

希望本文对你有帮助。

相关推荐
1-1=02 天前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
1-1=05 天前
C# IO和序列化
c#·.net·.netcore
宝桥南山6 天前
.NET 11 - 尝试一下Blazor中的新特性SupplyParameterFromTempData
microsoft·微软·c#·asp.net·.net·.netcore
1-1=07 天前
C# 特性(Attribute)
c#·.net·.netcore
淡海水7 天前
10-01-互操作-C#与C++边界的内存管理
unity·c#·游戏引擎·.netcore·gc
1-1=08 天前
C# 反射
c#·.net·.netcore
1-1=09 天前
C# 泛型
c#·.net·.netcore
淡海水11 天前
09-01-内存-Unity资源生命周期全景
unity·c#·游戏引擎·.netcore·gc
1-1=011 天前
.NET Core 编译技术
.net·.netcore
1-1=012 天前
.NET Core 文件系统
.net·.netcore·1024程序员节