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

Note: the bellow was for .NET Core < 3, which came without WinForms on Windows.

However, it is still valid if you need to compile something with WinForms on Linux, since .NET Core WinForms only runs on Windows.

Mixing frameworks is certainly one way to go - but then, why do you use .NET Core ?

But what you can do is port the mono implementation of System.Windows.Forms to NetStandard.
Such as here: https://github.com/ststeiger/System.CoreFX.Forms


for .Net 6 the .csproj file should contain:

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

Note the "-windows" in the target framework.

UseWPF is optional.


What you need is "frameworkAssemblies", for example:

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

Working with Clipboard also requires setting the main thread as STA, so don't forget to add [STAThread] to Main() in your application.


For VS2019 .NET Core 3.1:

  1. right-mouse click on the project and select Unload Project
  2. right-mouse click on the project and select "Edit foobar.csproj"
  3. Example of using WPF and Winforms in .NET Core 3.1: where I added the UseWPF and UseWindowsForms tags. Also I changed Microsoft.NET.Sdk to Microsoft.NET.Sdk.WindowsDesktop to be able to use also 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. save and right-mouse click on the project again and select Reload Project