【C++】获取指定点所在屏幕的尺寸

问题

多个显示器时,获取指定点所在的显示器的尺寸。

分析

解决

cpp 复制代码
#include "WinUser.h"

void GetRectByPoint(CPoint point, CRect& rectRes)
{
	//获取显示屏幕个数
	int nCount = GetSystemMetrics(SM_CMONITORS);
	if (nCount < 0)
		return;
	
	DISPLAY_DEVICE device;
	SecureZeroMemory(&device, sizeof(device));
	device.cb = sizeof(device);
	DEVMODE devMode;
	SecureZeroMemory(&devMode, sizeof(devMode));
	devMode.dmSize = sizeof(devMode);
	
	// 获取所有显示屏幕的位置
	std::vector<CRect> vScreenRet;
	for (int nIndex = 0; nIndex < nCount; ++nIndex)
	{
		if (!EnumDisplayDevices(NULL, nIndex, &device, 0)
			|| !EnumDisplaySettings(device.DeviceName, ENUM_CURRENT_SETTINGS, &devMode))
			continue;
	
		CRect rc(devMode.dmPosition.x, devMode.dmPosition.y, devMode.dmPosition.x + devMode.dmPelsWidth, devMode.dmPosition.y + devMode.dmPelsHeight);
		vScreenRet.push_back(rc);
	}
	
	// 匹配指定点所在显示器
	for (const CRect& rc : vScreenRet)
	{
		if (!::PtInRect(rc, point))
			continue;
		resRt = rc;
		break;
	}
}


int main()
{
	// 给定点坐标
	CPoint point;
	
	// 获取显示器尺寸
	CRect rect;
	GetRectByPoint(point, rect);
	// 输出获取到的数据
	cout<<"rect width: " << rect.right-rect.left << endl; 
	cout<<"rect height: " << rect.bottom-rect.top << endl; 
	return 0;
}

OK!搞定!

相关推荐
律宏阔2 小时前
WSL Docker 端口明明空闲,但就是绑不上端口
linux·windows
律宏阔2 小时前
Windows 禁用联想笔记本所有 Lenovo 后台服务
windows
律宏阔2 小时前
WSL 突然断网,无法 ping 内网或外网
linux·windows
codigger2 小时前
ObjectSense:一门千行内核、把可靠性写进骨子里的面向对象脚本语言
开发语言·编程·编程语言
小小龙学IT2 小时前
Boost.Interprocess 开源 C++ 进程间通信库深度解析
c++·开源
倒头就睡的小比特5 天前
算法竞赛C++常用的STL
c++·算法
weilx12345 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
rockmelodies5 天前
# Windows Server2008 R2 Standard(SP1镜像U盘)重置本地管理员密码【完整详细步骤】
windows·密码破解
伞伞悦读6 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python