我已经查看了每个类似的问题,但没有一个对我有用。我正在编写一个 winForm 来显示屏幕系数。我尝试从注册表中读取(不起作用)我尝试使用DLL“gdi32.dll”,它可以工作,但只能在Win10上运行,不能在Win7上运行。 我也尝试过:
float dpiX, dpiY;
using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
{
dpiX = graphics.DpiX;
dpiY = graphics.DpiY;
}
但它也不起作用。 我知道这个问题被重复了,但之前问题中的所有答案都没有帮助,所以这就是为什么我要打开一个新问题。 那么,有人可以帮助我吗?
您可以将 GetDpiForWindow 与清单一起使用。
uint nDPI = GetDpiForWindow(this.Handle);
我明白=>
100% : 96
125% : 120
150% : 144
175% : 168
声明=>
[DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern uint GetDpiForWindow(IntPtr hwnd);
清单=>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitor</dpiAwareness>
</windowsSettings>
</application>
没有清单文件:您必须在程序启动后立即设置SetProcessDPIAware()。它将进程默认 DPI 感知设置为系统 DPI 感知。否则它总是返回 100%。
internal static class Program
{
[DllImport("user32.dll")]
private static extern bool SetProcessDPIAware();
static void Main()
{
SetProcessDPIAware(); //sets the process-default DPI awareness to system-DPI
int scale = GetDpiScaleFactor();
Console.WriteLine(scale);
}
static int GetDpiScaleFactor()
{
const int _DEFAULT_DPI = 96;
Graphics gr = Graphics.FromImage(new Bitmap(1, 1)); //A Graphics object is needed for native DPI detection.
return (int)(gr.DpiX / _DEFAULT_DPI * 100); //In percentages, as shown in Windows
}
}
}