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

Ale*_*uts 10 .net .net-core project.json

我已经创建了.NET Core类库并尝试针对net40框架构建它.我想从System.Windows.Forms程序集中使用Clipboard类.我怎样才能做到这一点?

我的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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Lou*_*ers 51

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

<PropertyGroup>
     <TargetFramework>net6.0-windows</TargetFramework>
     <UseWPF>true</UseWPF>
     <UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)

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

UseWPF是可选的。


juF*_*uFo 43

对于 VS2019 .NET Core 3.1:

  1. 右键单击项目并选择卸载项目
  2. 右键单击项目并选择“编辑 foobar.csproj”
  3. 在 .NET Core 3.1 中使用 WPF 和 Winforms 的示例:我在其中添加了 UseWPF 和 UseWindowsForms 标记。此外,我改变了Microsoft.NET.SdkMicrosoft.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>
...
Run Code Online (Sandbox Code Playgroud)
  1. 保存并再次右键单击项目并选择重新加载项目

  • 谢谢。在没有 WPF 的情况下使用 Windows 窗体还需要我设置 `&lt;Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"&gt;`。 (5认同)
  • 我需要 Windows 目标平台来完成这项工作,例如“&lt;TargetFramework&gt;net6.0-windows&lt;/TargetFramework&gt;”。否则,构建时会出现错误“目标平台必须设置为 Windows” (4认同)

svi*_*ick 14

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

"frameworks": {
  "netstandard1.6": {
    "dependencies": {
      "NETStandard.Library": "1.6.0"
    }
  },
  "net40": {
    "frameworkAssemblies": {
      "System.Windows.Forms": {}
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

与工作Clipboard还需要设置主线程为STA,所以不要忘记添加[STAThread]Main()您的应用程序.

  • 如何在新的配置文件格式.csproj中做同样的事情? (15认同)
  • @ZEE 你知道 .csproj 中有什么例子吗? (2认同)