How to get Windows Display settings?

2019-01-02 18:32发布

There is setting for Display in Windows 7 (Control Panel -> Display). It allows to change the size of the text and other items on the screen. I need to get this setting to be able to switch on/switch off some functionality in my C# application based on the setting value. Is that possible?

标签: c# windows dpi
10条回答
高级女魔头
2楼-- · 2019-01-02 18:45

Here's a solution that works nicely in Windows 10. There's no need for DPI awareness or anything.

public static int GetWindowsScaling()
{
    return (int)(100 * Screen.PrimaryScreen.Bounds.Width / SystemParameters.PrimaryScreenWidth);
}
查看更多
皆成旧梦
3楼-- · 2019-01-02 18:48

This is a very old question, but since Windows 8.1, one can use various other functions, like GetDpiForWindow

In C#:

[DllImport("user32.dll")]
static extern int GetDpiForWindow(IntPtr hWnd);

public float GetDisplayScaleFactor(IntPtr windowHandle)
{
    try
    {
        return GetDpiForWindow(windowHandle) / 96f;
    }
    catch
    {
        // Or fallback to GDI solutions above
        return 1;
    }
}

For this to work correctly on Windows 10 anniversary, you need to add an app.manifest to your C# project:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
          manifestVersion="1.0">
  <application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <!-- The combination of below two tags have the following effect : 
      1) Per-Monitor for >= Windows 10 Anniversary Update
      2) System < Windows 10 Anniversary Update -->
      <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitor</dpiAwareness>
      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">True/PM</dpiAware>
    </windowsSettings>
  </application>

</assembly>
查看更多
大哥的爱人
4楼-- · 2019-01-02 18:56

I think this should provide you with the information you are looking for:

http://www.pinvoke.net/default.aspx/user32.getsystemmetrics

http://pinvoke.net/default.aspx/Enums.SystemMetric

Edit - oh sorry it looks like there is an easier way to get this information now without a pinvoke,

http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.aspx

查看更多
浪荡孟婆
5楼-- · 2019-01-02 18:57

This setting is the screen DPI, or dots per inch.

Read it like so:

float dpiX, dpiY;
Graphics graphics = this.CreateGraphics();
dpiX = graphics.DpiX;
dpiY = graphics.DpiY;

I don't think it's possible at the moment for the X and Y values to be different. A value of 96 corresponds to 100% font scaling (smaller), 120 corresponds to 125% scaling (medium) and 144 corresponds to 150% scaling (larger). However, users are able to set values other than these standard ones.

Do be aware that unless your application is declared to be DPI aware, then the values you observe may be subject to DPI virtualization.

查看更多
登录 后发表回答