如何在.NET Core 3.1控制台应用中获取Windows当前屏幕分辨率并判断是否为1024x768
纯C#实现Windows当前屏幕分辨率检测(替代批处理)
没问题,我来帮你把这段批处理逻辑转换成纯C#代码,完全不需要启动CMD进程,直接在.NET Core 3.1控制台应用里就能实现,还能直接加入你要的if-else判断逻辑。
下面给你两种可行的方案,你可以根据自己的需求选择:
方案一:使用System.Windows.Forms(直观易读)
这种方式代码更简洁易懂,但需要给控制台项目添加System.Windows.Forms的NuGet依赖:
- 在Visual Studio 2019里右键项目 → 管理NuGet程序包
- 搜索并安装
System.Windows.Forms包 - 打开项目的
.csproj文件,确保添加了<UseWindowsForms>true</UseWindowsForms>配置(如果没有的话手动加上)
然后就可以用下面的代码:
using System; using System.Windows.Forms; namespace ScreenResolutionChecker { class Program { static void Main(string[] args) { // 获取主屏幕的当前分辨率(多屏场景可替换为指定屏幕) int currentWidth = Screen.PrimaryScreen.Bounds.Width; int currentHeight = Screen.PrimaryScreen.Bounds.Height; Console.WriteLine($"当前屏幕分辨率:{currentWidth}x{currentHeight}"); // 实现你要的分辨率判断逻辑 if (currentWidth == 1024 && currentHeight == 768) { Console.WriteLine("✅ 当前分辨率是1024x768"); } else { Console.WriteLine($"❌ 当前分辨率不是1024x768,实际为{currentWidth}x{currentHeight}"); } Console.WriteLine("按任意键退出..."); Console.ReadKey(); } } }
方案二:调用Windows原生API(无额外依赖)
如果不想添加WinForms依赖,可以直接用P/Invoke调用Windows系统API,纯控制台环境就能运行:
using System; using System.Runtime.InteropServices; namespace ScreenResolutionChecker { class Program { // 导入Windows系统API函数 [DllImport("user32.dll")] private static extern int GetSystemMetrics(int nIndex); // API参数常量定义 private const int SM_CXSCREEN = 0; // 获取屏幕宽度 private const int SM_CYSCREEN = 1; // 获取屏幕高度 static void Main(string[] args) { int currentWidth = GetSystemMetrics(SM_CXSCREEN); int currentHeight = GetSystemMetrics(SM_CYSCREEN); Console.WriteLine($"当前屏幕分辨率:{currentWidth}x{currentHeight}"); // 分辨率判断逻辑 if (currentWidth == 1024 && currentHeight == 768) { Console.WriteLine("✅ 当前分辨率是1024x768"); } else { Console.WriteLine($"❌ 当前分辨率不是1024x768,实际为{currentWidth}x{currentHeight}"); } Console.WriteLine("按任意键退出..."); Console.ReadKey(); } } }
两种方案都能准确获取当前屏幕的实际分辨率(不是最大分辨率),并且完全替代你原来的批处理逻辑,不需要任何CMD调用~
内容的提问来源于stack exchange,提问作者haseakash2010




