winform实时获取系统dpi

环境: window10

框架:4.5.2

由于 windows10的DPI设置 无法直接获取屏幕的真实长宽
获取长宽代码
int iH = Screen.PrimaryScreen.Bounds.Height;
int iW = Screen.PrimaryScreen.Bounds.Width;

两种方法:
1、使用上边代码获取缩放后的长宽
iH*DPI(1.25)=真实高度
DPI获取方法:

#region Dll引用
[DllImport("User32.dll", EntryPoint = "GetDC")]
private extern static IntPtr GetDC(IntPtr hWnd);

[DllImport("User32.dll", EntryPoint = "ReleaseDC")]
private extern static int ReleaseDC(IntPtr hWnd, IntPtr hDC);

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

[DllImport("User32.dll")]
public static extern int GetSystemMetrics(int hWnd);

const int DESKTOPVERTRES = 117;
const int DESKTOPHORZRES = 118;
        
const int SM_CXSCREEN = 0;
const int SM_CYSCREEN = 1;

#endregion


 /// <summary>
 /// 获取DPI缩放比例
 /// </summary>
 /// <param name="dpiscalex"></param>
 /// <param name="dpiscaley"></param>
 public static void GetDPIScale(ref float dpiscalex, ref float dpiscaley)
 {
      int x = GetSystemMetrics(SM_CXSCREEN);
      int y = GetSystemMetrics(SM_CYSCREEN);
      IntPtr hdc = GetDC(IntPtr.Zero);
      int w = GetDeviceCaps(hdc, DESKTOPHORZRES);
      int h = GetDeviceCaps(hdc, DESKTOPVERTRES);
      ReleaseDC(IntPtr.Zero, hdc);
      dpiscalex = (float)w / x;
      dpiscaley = (float)h / y;
  }

2、直接获取分辨率

/// <summary>
/// 获取分辨率
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
private static void GetResolving(ref int width, ref int height)
{
     IntPtr hdc = GetDC(IntPtr.Zero);
     width = GetDeviceCaps(hdc, DESKTOPHORZRES);
     height = GetDeviceCaps(hdc, DESKTOPVERTRES);
     ReleaseDC(IntPtr.Zero, hdc);
}

 

posted @ 2024-09-03 18:41  卡萨丁·周  阅读(22)  评论(0编辑  收藏  举报