首页 > 解决方案 > 从其句柄 (HMONITOR) 获取监视器索引

问题描述

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

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

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

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

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

标签: c++windowsmultiple-monitors

解决方案


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

推荐阅读