'Forms' does not exist in the namespace system.windows

前端 未结 4 823
终归单人心
终归单人心 2020-12-01 03:37

I have just started working on c#, and was fiddling with some code sample that I got from some forum.

This code is using a namespace using system.windows.forms

相关标签:
4条回答
  • 2020-12-01 03:48

    If you are writing Windows Forms code in a .Net Core app, then it's very probable that you run into this error:

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

    If you are using the Sdk style project file (which is recommended) your *.csproj file should be similar to this:

    <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
      <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <OutputType>WinExe</OutputType>
        <UseWindowsForms>true</UseWindowsForms>
        <RootNamespace>MyAppNamespace</RootNamespace>
        <AssemblyName>MyAppName</AssemblyName>
        <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Microsoft.Windows.Compatibility" Version="3.0.0" />
      </ItemGroup>
    </Project>
    

    Pay extra attention to these lines:

    <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
    <OutputType>WinExe</OutputType>
    <UseWindowsForms>true</UseWindowsForms>
    <PackageReference Include="Microsoft.Windows.Compatibility" Version="3.0.0" />
    

    Note that if you are using WPF while referencing some WinForms libraries you should add <UseWPF>true</UseWPF> as well.

    0 讨论(0)
  • 2020-12-01 03:59

    You may encounter this problem if you have multiple projects inside a solution and one of them is physically located inside solution folder. I solved this by right click on this folder inside Solution tree -> then pressing "exclude from project"

    0 讨论(0)
  • 2020-12-01 04:07

    Expand the project in Solution Tree, right click on References, Add Reference, Select System.Windows.Forms on Framework tab.

    You need to add reference to some non-default assemblies sometimes.

    0 讨论(0)
  • 2020-12-01 04:12

    In case someone runs into this error when trying to reference Windows Forms components in a .NET Core 3+ WPF app (which is actually not uncommon). The solution is to go into the .csproj file (double click it in VS2019) and add it to the property group node containing the target frameworks. Like this:

    <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
        <UseWPF>true</UseWPF>
        <UseWindowsForms>true</UseWindowsForms>
    </PropertyGroup>
    
    0 讨论(0)
提交回复
热议问题