DPI.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include <ShellScalingAPI.h>
  3. // Definition: relative pixel = 1 pixel at 96 DPI and scaled based on actual DPI.
  4. class CDPI
  5. {
  6. public:
  7. CDPI(HWND hwnd = NULL) : m_Initialized(false), m_dpi(96)
  8. {
  9. m_hWnd = hwnd;
  10. }
  11. void Update(int dpi) { m_dpi = dpi; m_Initialized = true; }
  12. // Get screen DPI.
  13. int GetDPI() { Init(); return m_dpi; }
  14. // Convert between raw pixels and relative pixels.
  15. int Scale(int x) { Init(); return MulDiv(x, m_dpi, 96); }
  16. int UnScale(int x) { Init(); return MulDiv(x, 96, m_dpi); }
  17. // Invalidate any cached metrics.
  18. void Invalidate() { m_Initialized = false; }
  19. void SetHwnd(HWND hwnd) { m_hWnd = hwnd; m_Initialized = false; Init(); }
  20. private:
  21. void Init()
  22. {
  23. if (m_Initialized == false)
  24. {
  25. if (m_hWnd != NULL)
  26. {
  27. HMODULE hUser32 = LoadLibrary(_T("USER32.dll"));
  28. if (hUser32)
  29. {
  30. //windows 10
  31. typedef UINT(__stdcall *GetDpiForWindow)(HWND hwnd);
  32. GetDpiForWindow getDpi = (GetDpiForWindow)GetProcAddress(hUser32, "GetDpiForWindow");
  33. if (getDpi)
  34. {
  35. int dpi = getDpi(m_hWnd);
  36. this->Update(dpi);
  37. m_Initialized = true;
  38. }
  39. else
  40. {
  41. //windows 8
  42. auto monitor = MonitorFromWindow(m_hWnd, MONITOR_DEFAULTTONEAREST);
  43. HMODULE shCore = LoadLibrary(_T("Shcore.dll"));
  44. if (shCore)
  45. {
  46. typedef HRESULT(__stdcall *GetDpiForMonitor)(HMONITOR, UINT, UINT*, UINT*);
  47. GetDpiForMonitor monDpi = (GetDpiForMonitor)GetProcAddress(shCore, "GetDpiForMonitor");
  48. if (monDpi)
  49. {
  50. UINT x = 0;
  51. UINT y = 0;
  52. monDpi(monitor, MDT_EFFECTIVE_DPI, &x, &y);
  53. this->Update(x);
  54. m_Initialized = true;
  55. }
  56. }
  57. }
  58. }
  59. }
  60. if (m_Initialized == false)
  61. {
  62. HDC hdc = GetDC(m_hWnd);
  63. if (hdc)
  64. {
  65. m_dpi = GetDeviceCaps(hdc, LOGPIXELSX);
  66. ReleaseDC(NULL, hdc);
  67. m_Initialized = true;
  68. }
  69. }
  70. }
  71. }
  72. private:
  73. bool m_Initialized;
  74. int m_dpi;
  75. HWND m_hWnd;
  76. };