WPF 获取系统 DPI 的多种方法
2021-03-01 03:25
标签:sed ase transform 保存 isp 情况下 性能 ESS graph WPF 获取系统 DPI 的多种方法 首先,定义如下结构体来分别保存 X 方向 和 Y 方向的分量值,通常情况下两个值是一致的。 public struct Dpi public double Y { get; set; } public Dpi(double x, double y) var dpiX = 96.0; if (source?.CompositionTarget != null) return new Dpi(dpiX, dpiY); [DllImport("gdi32.dll")] [DllImport("user32.dll")] [DllImport("user32.dll")] public static Dpi GetDpiByWin32() var dpiX = GetDeviceCaps(hDc, LOGPIXELSX); ReleaseDC(IntPtr.Zero, hDc); var dpiXProperty = typeof(SystemParameters).GetProperty("DpiX", bindingFlags); var dpiX = 96.0; if (dpiXProperty != null) if (dpiYProperty != null) return new Dpi(dpiX, dpiY); public static Dpi GetDpiByGraphics() using (var graphics = Graphics.FromHwnd(IntPtr.Zero)) return new Dpi(dpiX, dpiY); public static Dpi GetDpiByManagement() using (var mc = new ManagementClass("Win32_DesktopMonitor")) return new Dpi(dpiX, dpiY); SystemEvents.DisplaySettingsChanged - SystemEvents Class 原文链接:https://blog.csdn.net/Iron_Ye/article/details/83053393 WPF 获取系统 DPI 的多种方法 标签:sed ase transform 保存 isp 情况下 性能 ESS graph 原文地址:https://www.cnblogs.com/javalinux/p/14450515.html
由于 WPF 的尺寸单位和系统的 DPI 相关,我们有时需要获取 DPI 值来进行一些界面布局的调整,本文汇总了一些 WPF 程序中获取系统 DPI 的方法。
{
public double X { get; set; }
{
X = x;
Y = y;
}
}
CompositionTarget
public static Dpi GetDpiFromVisual(Visual visual)
{
var source = PresentationSource.FromVisual(visual);
var dpiY = 96.0;
{
dpiX = 96.0 * source.CompositionTarget.TransformToDevice.M11;
dpiY = 96.0 * source.CompositionTarget.TransformToDevice.M22;
}
}
Win32 API
private const int LOGPIXELSX = 88;
private const int LOGPIXELSY = 90;
private static extern int GetDeviceCaps(IntPtr hdc, int index);
private static extern IntPtr GetDC(IntPtr hWnd);
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDc);
{
var hDc = GetDC(IntPtr.Zero);
var dpiY = GetDeviceCaps(hDc, LOGPIXELSY);
return new Dpi(dpiX, dpiY);
}
SystemParameters
public static Dpi GetDpiBySystemParameters()
{
const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Static;
var dpiYProperty = typeof(SystemParameters).GetProperty("DpiY", bindingFlags);
var dpiY = 96.0;
{
dpiX = (double)dpiXProperty.GetValue(null, null);
}
{
dpiY = (double)dpiYProperty.GetValue(null, null);
}
}
Graphics
添加 System.Drawing 引用
{
double dpiX;
double dpiY;
{
dpiX = graphics.DpiX;
dpiY = graphics.DpiY;
}
}
ManagementClass
System.Management 引用
{
var dpiX = 96.0;
var dpiY = 96.0;
{
using (var moc = mc.GetInstances())
{
// there may be many, to filter the ones you are interested in
foreach (var mo in moc)
{
dpiX = double.Parse(mo.Properties["PixelsPerXLogicalInch"].Value.ToString());
dpiY = double.Parse(mo.Properties["PixelsPerYLogicalInch"].Value.ToString());
}
}
}
}
处于 跨平台、多屏幕、性能 等方面的综合考虑,推荐使用 CompositionTarget 方法。另外,监听系统 DPI 变化的方法:
WM_DPICHANGED message
参考资料
Best way to get DPI value in WPF
How can I get the DPI in WPF?
文章标题:WPF 获取系统 DPI 的多种方法
文章链接:http://soscw.com/index.php/essay/58365.html