Search code examples
c#.netwinforms.net-core.net-standard

.NET class library with WinForms dependency targeting .NET Standard 2.0


I am migrating a .NET Framework class library that now needs to be compatible with both .NET Framework and .NET Core applications; the library relies on the System.Windows.Forms namespace.
To achieve this compatibility, I decided to target .NET Standard 2.0 for my class library since it can be used by both .NET Framework and .NET Core projects.
However, I'm encountering an issue with the following error:

Error CS0234 The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)

Here is my class and project setup:

Class:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace NetUtils
{
    public class NDUtils
    {
        public void ShowConnectDialog(Form ParentForm)
        {
            zDisplayDialog(ParentForm, 1);
        }

        public void ShowDisconnectDialog(Form ParentForm)
        {
            zDisplayDialog(ParentForm, 2);
        }

        private void zDisplayDialog(Form poParentForm, int piDialog)
        {
            int num = -1;
            int phWnd = 0;
            if (poParentForm != null)
            {
                phWnd = poParentForm.Handle.ToInt32();
            }
            switch (piDialog)
            {
            case 1:
                num = WNetConnectionDialog(phWnd, 1);
                break;
            case 2:
                num = WNetDisconnectDialog(phWnd, 1);
                break;
            }
            if (num > 0)
            {
                throw new Win32Exception(num);
            }
            poParentForm.BringToFront();
        }

        [DllImport("mpr.dll")]
        private static extern int WNetConnectionDialog(int phWnd, int piType);

        [DllImport("mpr.dll")]
        private static extern int WNetDisconnectDialog(int phWnd, int piType);
    }
}

Csproj:

<!-- also tried Microsoft.NET.Sdk to no avail -->
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
  </PropertyGroup>

</Project>

I understand that System.Windows.Forms is not part of .NET Standard 2.0, but I need to use it in my library. How can I resolve this issue while maintaining compatibility with both .NET Framework and .NET Core?


Solution

  • I'd step away from .NET Standard and multitarget .NET Framework and .NET Core instead.