You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET6控制台程序报CS0234缺少System.Windows.Forms引用如何修复

问题描述
  • 执行命令 dotnet new console -o MyApp -f net6.0 创建了.NET 6控制台程序
  • 修改Program.cs文件,写入如下测试代码:
global using System.Windows.Forms;

System.Console.WriteLine("Primary screen resolution: " + SystemInformation.PrimaryMonitorSize);
System.Console.WriteLine("Virtual size: " + SystemInformation.VirtualScreen);
System.Console.WriteLine("Monitors count: " + SystemInformation.MonitorCount);
  • 在项目路径 PS C:\Users\box\Desktop\dotnet\MyApp> 下执行 dotnet run 时出现构建错误,报错内容:
C:\Users\box\Desktop\dotnet\MyApp\Program.cs(1,29): error CS0234: The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?) [C:\Users\box\Desktop\dotnet\MyApp\MyApp.csproj]

The build failed. Fix the build errors and run again.
  • 开发时使用系统自带记事本编写代码,已确认代码中使用的SystemInformation类属于System.Windows.Forms命名空间、对应依赖为System.Windows.Forms.dll,需要解决依赖缺失导致的编译失败问题。
解决方法

报错的直接原因是普通.NET控制台项目默认不会引入Windows Forms相关的桌面组件依赖,按以下步骤修复即可:

  1. 打开项目目录下的MyApp.csproj文件(用记事本就能直接打开编辑),将原有内容替换为以下配置:
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0-windows</TargetFramework>
        <UseWindowsForms>true</UseWindowsForms>
      </PropertyGroup>
    </Project>
    
    *关键改动有两点:一是将目标框架修改为带-windows后缀的Windows专属版本,因为Windows Forms是Windows平台专属组件,不支持跨平台运行;二是添加<UseWindowsForms>true</UseWindowsForms>配置,编译时会自动引入Windows Forms相关的所有程序集,不需要手动单独添加dll引用。
  2. 保存csproj文件后,在项目目录下依次执行以下命令:
    dotnet restore
    dotnet run
    
    等待依赖还原完成后,程序就能正常编译运行,输出屏幕分辨率、虚拟屏幕尺寸、显示器数量等参数。
  • 补充说明:不需要额外安装特殊编辑工具,记事本完全可以满足代码编写需求,只要本地已经正确安装.NET 6 SDK就能完成所有操作,不需要安装Visual Studio这类重型IDE。

内容的提问来源于stack exchange,提问作者Ultra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 06:12:13