从其句柄 (HMONITOR) 获取监视器索引 [英] Get monitor index from its handle (HMONITOR)

查看:34
本文介绍了从其句柄 (HMONITOR) 获取监视器索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣根据监视器句柄获取监视器索引(基于 1,以匹配 Windows 编号).

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

用例:给定一个窗口的矩形,我想知道它所属的监视器.我可以使用 <代码>MonitorFromRect:

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:不确定是否重复,但我一直环顾四周,但没有运气.

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

推荐答案

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

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
}

这篇关于从其句柄 (HMONITOR) 获取监视器索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆