C# 获取当前屏幕DPI

1.通过Graphics类获取

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

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

性能有点水,31ms。不建议使用这个方案

注:这个获取方式在程序运行过程中,变更文本显示比例时,通过以上方式无法获取到最新的DPI值。

2. CompositionTarget 

1     var source = PresentationSource.FromVisual(this);
2     if (source?.CompositionTarget != null)
3     {
4         var dpiX = source.CompositionTarget.TransformToDevice.M11;
5         Debug.WriteLine($"CompositionTargetRatio:{dpiX}");
6     }

这个获取方式,同上,也存在一定局限。程序启动后,无法获取时时变更的DPI。性能比Graphics方案好很多,几乎不耗时。

3. SystemParameters

通过反射,获取Dpi属性值

1     var dpiXProperty = typeof(SystemParameters).GetProperty("DpiX", BindingFlags.NonPublic | BindingFlags.Static);
2     var dpiYProperty = typeof(SystemParameters).GetProperty("Dpi", BindingFlags.NonPublic | BindingFlags.Static);
3     var dpiX = (int)dpiXProperty.GetValue(null, null);
4     var dpiY = (int)dpiYProperty.GetValue(null, null);
5     var dpixRatio = dpiX / 96;
6     var dpiyRatio = dpiY / 96;

这个获取方式,程序程序启动后也是无法获取变更的DPI。但性能比Graphics方案好很多,几乎不耗时。

方案3相比1、2不需要窗口句柄等UI层,软件运行期间不会变更DPI的场景,推荐使用此方案

4. 通过user32获取DPI

先添加一下user32函数:GetDpiForMonitor

1         [DllImport("user32.dll")]
2         private static extern uint GetDpiForWindow([In] IntPtr hmonitor);

获取窗口DPI:

1     var dpiForWindow = GetDpiForWindow(new WindowInteropHelper(this).Handle);
2     var windowRatio = (double)dpiForWindow / 96.0;
3     Debug.WriteLine($"windowRatio:{dpiRatioX}");

输出的结果:

 也可以通过类似方法,获取当前屏幕的DPI,值是一样的:

1     var monitor = MonitorFromWindow(new WindowInteropHelper(this).Handle, MonitorDefaultTo.MONITOR_DEFAULTTONEAREST);
2     uint dpiX, dpiY;
3     GetDpiForMonitor(monitor, DpiType.Effective, out dpiX, out dpiY);
4     var dpiRatioX = (double)dpiX / 96.0;

调用的函数:

 1         [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
 2         internal static extern IntPtr MonitorFromWindow(IntPtr hwnd, MonitorDefaultTo dwFlags);
 3         [DllImport("Shcore.dll")]
 4         private static extern IntPtr GetDpiForMonitor([In] IntPtr hmonitor, [In] DpiType dpiType, [Out] out uint dpiX, [Out] out uint dpiY);
 5         internal enum MonitorDefaultTo
 6         {
 7             MONITOR_DEFAULTTONULL,
 8             MONITOR_DEFAULTTOPRIMARY,
 9             MONITOR_DEFAULTTONEAREST,
10         }
11         public enum DpiType
12         {
13             Effective = 0,
14             Angular = 1,
15             Raw = 2,
16         }

即时获取当前窗口所在屏幕的DPI,推荐使用此方案。

其它获取方式,比如

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

 

posted @ 2017-08-25 18:23  唐宋元明清2188  阅读(7641)  评论(0编辑  收藏  举报