Search code examples
c++windowsmultiple-monitors

Get monitor index from its handle (HMONITOR)


I'm interested in getting the monitor index (1-based, to match Windows numbering) given the monitor handle.

Case of use: given a window's rect I want to know the monitor it belongs to. I can get the handle of the monitor using MonitorFromRect:

// RECT rect
const HMONITOR hMonitor = MonitorFromRect(rect, MONITOR_DEFAULTTONEAREST);

How can I get the monitor index from this handle?

PS: not sure if duplicate, but I've been looking around with no luck.


Solution

  • I found this post with the opposite question: finding the handle given the index (0-based in that case).

    Based on it I worked this solution:

    struct sEnumInfo {
      int iIndex = 0;
      HMONITOR hMonitor = NULL;
    };
    
    BOOL CALLBACK GetMonitorByHandle(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
    {
      auto info = (sEnumInfo*)dwData;
      if (info->hMonitor == hMonitor) return FALSE;
      ++info->iIndex;
      return TRUE;
    }
    
    int GetMonitorIndex(HMONITOR hMonitor)
    {
      sEnumInfo info;
      info.hMonitor = hMonitor;
    
      if (EnumDisplayMonitors(NULL, NULL, GetMonitorByHandle, (LPARAM)&info)) return -1;
      return info.iIndex + 1; // 1-based index
    }