c# 获取系统dpi

发布时间 2023-03-25 16:09:55作者: trykle

c# 获取系统dpi

正在搜索: c# 获取系统dpi
正在为你生成答案…

您可以使用以下代码获取当前屏幕的DPI:

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

其中,mainWindow是您的窗口对象。

如果是在命令行程序中获取呢,命令行程序中不存在mainWindow

如果是在命令行程序中获取,您可以使用以下代码:

Graphics currentGraphics = Graphics.FromHwnd(IntPtr.Zero);
double dpixRatio = currentGraphics.DpiX / 96;

其中,IntPtr.Zero表示当前屏幕的句柄。

根据我的测试,在不同程序中此方法将返回不同的值,如何永远返回系统的dpi呢?

如果您想要获取系统的DPI,可以使用以下代码:

[DllImport("gdi32.dll")]
static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

[DllImport("user32.dll")]
static extern IntPtr GetDC(IntPtr hWnd);

[DllImport("user32.dll")]
static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

const int LOGPIXELSX = 88;
const int LOGPIXELSY = 90;

IntPtr hdc = GetDC(IntPtr.Zero);
int dpiX = GetDeviceCaps(hdc, LOGPIXELSX);
int dpiY = GetDeviceCaps(hdc, LOGPIXELSY);
ReleaseDC(IntPtr.Zero, hdc);
double dpixRatio = dpiX / 96.0;

其中,LOGPIXELSX和LOGPIXELSY是常量,分别代表水平和垂直方向的DPI。