Home > Backend Development > C++ > How to Programmatically Retrieve Windows Display Scaling Factor in C#?

How to Programmatically Retrieve Windows Display Scaling Factor in C#?

Mary-Kate Olsen
Release: 2025-01-15 12:10:43
Original
496 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template