C# 获取分辨率比例缩放 作者:马育民 • 2024-08-16 19:26 • 阅读:10011 # 问题 通过鼠标钩子获取鼠标坐标,还是按照下图:`1920 x 1080` 显示的,所以是不正确的,应该是按照 `1920 / 125%`显示 [![](/upload/0/0/1IX8FiZ9bbAd.jpg)](/upload/0/0/1IX8FiZ9bbAd.jpg) ### 解决 ``` internal class ScreenScale { public const int DESKTOPHORZRES = 118; [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr ptr); [DllImport("gdi32.dll")] public static extern int GetDeviceCaps( IntPtr hdc, // handle to DC int nIndex // index of capability ); [DllImport("user32.dll", EntryPoint = "ReleaseDC")] public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDc); [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); public static float GetScreenScale() { var hdc = GetDC(GetDesktopWindow()); int nWidth = GetDeviceCaps(hdc, DESKTOPHORZRES); ReleaseDC(IntPtr.Zero, hdc); float f_Scale = (float)nWidth / (float)Screen.PrimaryScreen.Bounds.Width; return f_Scale; } ``` ### 使用 ``` float scale = ScreenScale.GetScreenScale(); ``` ### 注意 上面代码,必须在下面代码之前调用(之后在任意位置调用都可以),否则无法获取缩放比例: ``` if (Environment.OSVersion.Version.Major >= 6) { SetProcessDPIAware(); } ``` 上面代码的解释详见: https://www.malaoshi.top/show_1IX6DMSSMArT.html 原文出处:https://malaoshi.top/show_1IX8FifIbtNn.html