WinForm中Screen.Bounds返回错误分辨率值问题求助
Screen.Bounds 获取错误分辨率的排查方案
针对你遇到的.NET 4.6.2 WinForm应用中Screen.Bounds返回错误分辨率(实际1366×768却返回560×300)的问题,可尝试以下排查和解决方法:
确认目标屏幕对象:检查代码是否误获取了非主屏幕的Bounds。确保你调用的是
Screen.PrimaryScreen.Bounds,或遍历所有屏幕验证每个屏幕的分辨率:foreach (var screen in Screen.AllScreens) { Console.WriteLine($"屏幕:{screen.DeviceName},分辨率:{screen.Bounds.Width}×{screen.Bounds.Height}"); }强制配置系统级DPI感知:除了项目设置中的DPI感知选项,通过
app.manifest文件明确配置:
在项目的app.manifest中添加或修改以下节点:<application xmlns="urn:schemas-microsoft-com:asm.v3"> <windowsSettings> <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware> </windowsSettings> </application>确保项目属性中已选择该manifest文件(应用程序->资源->清单),然后重建项目。
排查DPI上下文修改代码:检查项目中是否存在通过P/Invoke调用
SetProcessDpiAwareness、SetProcessDpiAwarenessContext等API的代码,这类调用可能改变后续Screen.Bounds的返回值。若有,调整调用时机或移除不必要的DPI上下文修改。直接调用Windows API获取原始分辨率:绕过.NET的
Screen类,使用原生API获取桌面分辨率:using System.Runtime.InteropServices; public static class ScreenHelper { [DllImport("user32.dll")] private static extern bool GetDesktopResolution(out int width, out int height); public static (int Width, int Height) GetNativeDesktopResolution() { GetDesktopResolution(out int width, out int height); return (width, height); } } // 使用示例 var resolution = ScreenHelper.GetNativeDesktopResolution(); Console.WriteLine($"原生分辨率:{resolution.Width}×{resolution.Height}");若此方法返回正确值,说明
Screen类的调用受当前应用上下文影响,需进一步排查DPI相关配置。清理项目缓存并重建:删除解决方案的
bin、obj文件夹,重启Visual Studio后重新编译运行,排除缓存导致的异常。
内容的提问来源于stack exchange,提问作者Sabahat Hassan Raza
相关产品推荐
相关产品推荐

