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

希望本文对你有帮助。

相关推荐
weixin_379880924 天前
.Net Core WebApi集成Swagger
java·服务器·.netcore
The Future is mine6 天前
.Net Core 在Linux系统下创建服务
linux·运维·.netcore
*长铗归来*7 天前
ASP.NET Core Web API 中控制器操作的返回类型及Swagger
后端·c#·asp.net·.netcore
IDOlaoluo7 天前
VS2017 安装 .NET Core 2.2 SDK 教程(包括 dotnet-sdk-2.2.108-win-x64.exe 安装步骤)
.netcore
csdn_aspnet15 天前
使用 Entity Framework Code First 方法创建 ASP.NET Core 5.0 Web API
.netcore·webapi
小先生81215 天前
.NET Core项目中 Serilog日志文件配置
c#·.netcore
爱吃香蕉的阿豪15 天前
.NET Core 中 System.Text.Json 与 Newtonsoft.Json 深度对比:用法、性能与场景选型
数据库·json·.netcore
csdn_aspnet15 天前
ASP.NET Core 10.0 的主要变化
.netcore
何以解忧唯有撸码18 天前
c#造个轮子-取色器TakeColor(附源码)
winform·takecolr·取色器
csdn_aspnet18 天前
在 C# .NETCore 中使用 MongoDB(第 1 部分):驱动程序基础知识和插入文档
mongodb·.netcore