Home > Backend Development > C++ > How Can I Accurately Retrieve Windows Display Scaling Factor in C#?

How Can I Accurately Retrieve Windows Display Scaling Factor in C#?

Mary-Kate Olsen
Release: 2025-01-15 11:10:50
Original
369 people have browsed it

How Can I Accurately Retrieve Windows Display Scaling Factor in C#?

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

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!

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