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

Get monitor index from its handle (HMONITOR)

本文关键字:获取 监视器 索引 HMONITOR 句柄      更新时间:2023-10-16

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

使用案例:给定一个窗口的矩形,我想知道它所属的显示器。我可以使用MonitorFromRect获取显示器的手柄:

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

如何从此句柄获取监视器索引?

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

我发现这篇文章有相反的问题:找到给定索引的句柄(在这种情况下从 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
}