从其句柄中获取监视器索引 (HMONITOR)

Get monitor index from its handle (HMONITOR)

我有兴趣在给定监视器句柄的情况下获取监视器索引(从 1 开始,以匹配 Windows 编号)。

使用案例:给定一个window的rect我想知道它属于哪个监视器。我可以使用 MonitorFromRect:

获取监视器的句柄
// RECT rect
const HMONITOR hMonitor = MonitorFromRect(rect, MONITOR_DEFAULTTONEAREST);

如何从这个句柄中获取监视器索引?

PS:不确定是否重复,但我一直在四处寻找,但没有运气。

我发现 this post 有相反的问题:找到给定索引的句柄(在这种情况下从 0 开始)。

基于它我制定了这个解决方案:

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
}