Precisely Retrieving Windows Display Scaling in C# Applications
Adapting application behavior to match user-defined display settings, such as text and element sizing, is a frequent programming task. This article presents a robust C# method for accurately retrieving these settings.
While Graphics.DpiX
or DeviceCap.LOGPIXELSX
are traditional approaches, they may yield inaccurate scaling values, particularly on high-DPI displays.
A more reliable method involves leveraging the Windows API function GetDeviceCaps
to calculate the scaling factor. This function retrieves both logical and physical screen heights, allowing for a precise calculation.
Here's the improved C# code:
<code class="language-csharp">[DllImport("gdi32.dll")] static extern int GetDeviceCaps(IntPtr hdc, int nIndex); public enum DeviceCap { VERTRES = 10, DESKTOPVERTRES = 117, } private float GetScalingFactor() { using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { IntPtr desktop = g.GetHdc(); int logicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.VERTRES); int physicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.DESKTOPVERTRES); g.ReleaseHdc(desktop); return (float)physicalScreenHeight / logicalScreenHeight; // e.g., 1.25 = 125% } }</code>
This refined approach offers superior accuracy in determining the scaling factor across various display scaling levels, enabling more precise adjustments to application functionality based on the user's display configuration.
The above is the detailed content of How Can I Accurately Retrieve Windows Display Scaling Factor in C#?. For more information, please follow other related articles on the PHP Chinese website!