我有类似的问题。为了修复它,我检查了当前的 DPI 设置并在需要的地方水平和垂直缩放尺寸。这个帮助类提供水平和垂直比例:HDpiScale、VDpiScale。
用法:
MyControl.Height = (int) (MyControl.Height * util.VDpiScale);
MyControl.Width = (int) (MyControl.Width * util.HDpiScale);
仅当字体大小为 x1.25 时才有意义
public class PresentationUtils : IPresentationUtils
{
private double vDpiScale = -1;
private double hDpiScale = -1;
public double HDpiScale
{
get
{
if (hDpiScale < 0)
SetDpiScales();
return hDpiScale;
}
}
public double VDpiScale
{
get
{
if (vDpiScale < 0)
SetDpiScales();
return vDpiScale;
}
}
private void SetDpiScales()
{
vDpiScale = 1;
hDpiScale = 1;
IntPtr dc = GetDC(IntPtr.Zero);
try
{
int hPixels = GetDeviceCaps(dc, (int) DeviceCap.LOGPIXELSX);
int vPixels = GetDeviceCaps(dc, (int) DeviceCap.LOGPIXELSY);
vDpiScale = vPixels/96.0;
hDpiScale = hPixels/96.0;
}
finally
{
ReleaseDC(IntPtr.Zero, dc);
}
}
[DllImport("gdi32.dll")]
public static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
}
public enum DeviceCap
{
/// <summary>
/// Logical pixels inch in X
/// </summary>
LOGPIXELSX = 88,
/// <summary>
/// Logical pixels inch in Y
/// </summary>
LOGPIXELSY = 90,
}