Get monitor index from its handle (HMONITOR)

假装没事ソ 提交于 2019-12-24 20:30:21

问题


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.


回答1:


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
}


来源:https://stackoverflow.com/questions/54326892/get-monitor-index-from-its-handle-hmonitor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!