# C# 获取windows显示缩放比例

C#
public const int DESKTOPVERTRES = 117;
public const int DESKTOPHORZRES = 118;
public const int SM_CXSCREEN = 0;
public const int SM_CYSCREEN = 1;
public const int SM_REMOTESESSION = 0x1000;

[DllImport("user32.dll")]
public static extern IntPtr GetDC(IntPtr ptr);

[DllImport("user32.dll", EntryPoint = "ReleaseDC")]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDc);

[DllImport("gdi32.dll", EntryPoint = "GetDeviceCaps", SetLastError = true)]
public static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

[DllImport("user32.dll", EntryPoint = "GetSystemMetrics")]
public static extern int GetSystemMetrics(int mVal);


private bool GetSystemScale(out float x, out float y, out int sourceWidth, out int sourceHeight)
{
    x = 1;
    y = 1;
    sourceWidth = 0;
    sourceHeight = 0;
    IntPtr hdc = GetDC(IntPtr.Zero);
    if (hdc != IntPtr.Zero)
    {
        sourceWidth = GetDeviceCaps(hdc, DESKTOPHORZRES);
        sourceHeight = GetDeviceCaps(hdc, DESKTOPVERTRES);
        int screenWidth = GetSystemMetrics(SM_CXSCREEN);
        int screenHeight = GetSystemMetrics(SM_CYSCREEN);

        x = (sourceWidth * 1.0f / screenWidth);
        y = (sourceHeight * 1.0f / screenHeight);

        ReleaseDC(IntPtr.Zero, hdc);

        return true;
    }
    return false;
}