如何在 .NET Core class 库中使用 System.Windows.Forms

How to use System.Windows.Forms in .NET Core class library

我创建了 .NET Core class 库并尝试针对 net40 框架构建它。我想使用来自 System.Windows.Forms 程序集的剪贴板 class。我该怎么做?

我的 project.json 文件:

{
    "version": "1.0.0-*",

    "dependencies": {
        "NETStandard.Library": "1.6.0"
    },

    "frameworks": {
        "netstandard1.6": {
            "imports": "dnxcore50",
            "buildOptions": {
                "define": [
                    "NETCORE"
                ]
            },
            "dependencies": {
                "System.Threading": "4.0.11",
                "System.Threading.Thread": "4.0.0",
                "System.Threading.Tasks":  "4.0.11"
                }
        },
        "net40": {
            "buildOptions": {
                "define": [
                    "NET40"
                    ]
                },
            "dependencies": {
                // dependency should be here but there is no such dll
            }
        }
    }
}

我所有的 net40 特定代码都在 NET40 定义下。有什么想法吗?

你需要的是"frameworkAssemblies",例如:

"frameworks": {
  "netstandard1.6": {
    "dependencies": {
      "NETStandard.Library": "1.6.0"
    }
  },
  "net40": {
    "frameworkAssemblies": {
      "System.Windows.Forms": {}
    }
  }
}

使用 Clipboard 还需要将主线程设置为 STA,所以不要忘记在您的应用程序中将 [STAThread] 添加到 Main()

注意:以下是针对 .NET Core < 3 的,它在 Windows 上没有 WinForms。

但是,如果您需要在 Linux 上使用 WinForms 编译某些内容,它仍然有效,因为 .NET Core WinForms 仅在 Windows.

上运行

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

但是您可以做的是将 System.Windows.Forms 的单声道实现移植到 NetStandard。
比如这里: https://github.com/ststeiger/System.CoreFX.Forms

对于 VS2019 .NET Core 3.1:

  1. 鼠标右键单击项目并 select 卸载项目
  2. 在项目上单击鼠标右键,然后 select "Edit foobar.csproj"
  3. 在 .NET Core 3.1 中使用 WPF 和 Winforms 的示例:我在其中添加了 UseWPF 和 UseWindowsForms 标记。我也将 Microsoft.NET.Sdk 更改为 Microsoft.NET.Sdk.WindowsDesktop 以便也可以使用 wpf.
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWPF>true</UseWPF>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>
...
  1. 保存并再次右键单击项目,然后 select 重新加载项目

对于 .Net 6,.csproj 文件应包含:

<PropertyGroup>
     <TargetFramework>net6.0-windows</TargetFramework>
     <UseWPF>true</UseWPF>
     <UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>

注意目标框架中的“-windows”。

UseWPF 是可选的。