C# 获取当前屏幕DPI

C#

浏览数:388

2019-6-14

1.通过Graphics类获取

Graphics currentGraphics = Graphics.FromHwnd(new WindowInteropHelper(mainWindow).Handle);
double dpixRatio = currentGraphics.DpiX/96;

比如当前屏幕设置DPI设置1.5倍,可以通过如上通过后台获取。

2.通过Win32-ManagementClass

using (ManagementClass mc = new ManagementClass("Win32_DesktopMonitor"))
{
    using (ManagementObjectCollection moc = mc.GetInstances())
    {

        int PixelsPerXLogicalInch = 0; // dpi for x
        int PixelsPerYLogicalInch = 0; // dpi for y

        foreach (ManagementObject each in moc)
        {
            PixelsPerXLogicalInch = int.Parse((each.Properties["PixelsPerXLogicalInch"].Value.ToString()));
            PixelsPerYLogicalInch = int.Parse((each.Properties["PixelsPerYLogicalInch"].Value.ToString()));
        }
    }
}

值得一提的是,有主副屏屏幕的情况下,是获取不了副屏的DPI的!

注:屏幕的物理分辨率/真实分辨率/高宽缩放比例,可参考C# API 获取系统DPI缩放倍数跟分辨率大小

 

作者:唐宋元明清2188