【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!搞定!

相关推荐
澈2072 小时前
C++并查集:高效解决连通性问题
java·c++·算法
郝学胜-神的一滴3 小时前
Qt 入门 01-01:从零基础到商业级客户端实战
开发语言·c++·qt·程序人生·软件构建
测试员周周3 小时前
【Appium 系列】第06节-页面对象实现 — LoginPage 实战
开发语言·前端·人工智能·python·功能测试·appium·测试用例
宏笋4 小时前
C++ thread的detach()方法详解
c++
旖-旎4 小时前
深搜练习(单词搜索)(12)
c++·算法·深度优先·力扣
摇滚侠4 小时前
@Autowired 和 @Resource 的区别
java·开发语言
vortex54 小时前
PowerShell 的命令补全方案: PSReadLine + PSCompletions + argc + Carapace
windows·powershell
Wy_编程4 小时前
go语言中的结构体
开发语言·后端·golang
SeaTunnel4 小时前
(八)收官篇 | 数据平台最后一公里:数据集成开发设计与上线治理实战
java·大数据·开发语言·白鲸开源
Ujimatsu5 小时前
虚拟机安装Ubuntu 26.04.x服务器版(命令行版)(2026.5)
linux·windows·ubuntu