forked from anaisbetts/PerMonitorDpi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MonitorDpi.cs
50 lines (41 loc) · 1.65 KB
/
MonitorDpi.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
namespace PerMonitorDpi
{
using System;
using System.Windows;
using System.Windows.Interop;
/// <summary>
/// Определение DPI монитора
/// </summary>
/// <remarks>https://github.com/anaisbetts/PerMonitorDpi</remarks>
internal static class MonitorDpi
{
static bool? _isHighDpiMethodSupported = null;
public static bool IsHighDpiMethodSupported()
{
if (_isHighDpiMethodSupported != null) return _isHighDpiMethodSupported.Value;
_isHighDpiMethodSupported = SafeNativeMethods.DoesWin32MethodExist("shcore.dll", "SetProcessDpiAwareness");
return _isHighDpiMethodSupported.Value;
}
public static double GetScaleRatioForWindow(IntPtr hWnd)
{
var wpfDpi = 96.0 * PresentationSource.FromVisual(Application.Current.MainWindow).CompositionTarget.TransformToDevice.M11;
if (IsHighDpiMethodSupported() == false)
{
// Use System DPI
return wpfDpi / 96.0;
}
else
{
var monitor = SafeNativeMethods.MonitorFromWindow(hWnd, MonitorOpts.MONITOR_DEFAULTTONEAREST);
uint dpiX; uint dpiY;
SafeNativeMethods.GetDpiForMonitor(monitor, MonitorDpiType.MDT_EFFECTIVE_DPI, out dpiX, out dpiY);
return ((double)dpiX) / wpfDpi;
}
}
public static double GetScaleRatioForWindow(FrameworkElement This)
{
var hwndSource = PresentationSource.FromVisual(This) as HwndSource;
return GetScaleRatioForWindow(hwndSource.Handle);
}
}
}