Home >Backend Development >C++ >How to Programmatically Retrieve Windows Display Scaling Factor in C#?
Accessing Windows Display Settings in C#
Windows 7 and later versions provide a Control Panel setting allowing users to adjust text and UI element sizes. C# developers often need to retrieve this setting for dynamic application behavior.
A Practical Solution
Directly using graphics.DpiX
and DeviceCap.LOGPIXELSX
unexpectedly returns a fixed value (96 DPI) regardless of the actual scaling. To accurately determine the scaling factor, a different approach is necessary:
<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 for 125% scaling } }</code>
This code snippet leverages GetDeviceCaps
to compare logical and physical screen heights, providing a precise scaling factor. A result of 1.25, for instance, indicates a 125% scaling level.
The above is the detailed content of How to Programmatically Retrieve Windows Display Scaling Factor in C#?. For more information, please follow other related articles on the PHP Chinese website!