问题
多个显示器时,获取指定点所在的显示器的尺寸。
分析
- 之前整理过获取屏幕尺寸的方法:https://blog.csdn.net/m0_43605481/article/details/125024500
- 多显示器时,需要用到GetSystemMetrics 、EnumDisplayDevices 、EnumDisplaySettings函数
解决
            
            
              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!搞定!