一、方法一,使用 EnumDisplayMonitors 获取屏幕分辨率
#include <Windows.h>
#include <iostream>
BOOL CALLBACK EnumMonitor(HMONITOR handle, HDC hdc, LPRECT rect, LPARAM param) {
std::vector<MONITORINFO> *list = (std::vector<MONITORINFO>*)param;
MONITORINFO mi;
mi.cbSize = sizeof(mi);
GetMonitorInfo(handle, &mi);
std::cout << "is MONITORINFOF_PRIMARY:" << mi.dwFlags << std::endl;
list->push_back(mi);
return true;
}
int main(void) {
// 获取当前显示器的数目
int numbers = GetSystemMetrics(SM_CMONITORS);
std::cout << "numbers:" << numbers << std::endl;
std::vector<MONITORINFO> monitor_list;
EnumDisplayMonitors(NULL, NULL, EnumMonitor, (LPARAM)&monitor_list);
for (size_t i = 0; i < monitor_list.size(); ++i) {
std::cout << "width:" << (monitor_list[i].rcMonitor.right - monitor_list[i].rcMonitor.left) << std::endl;
std::cout << "height:" << (monitor_list[i].rcMonitor.bottom - monitor_list[i].rcMonitor.top) << std::endl;
}
getchar();
return 0;
}
但是这里获取到的分辨率大小是经过缩放显示之后的大小
二、方案二:使用 EnumDisplaySettingsExW 获取
上面获取的分辨率有一点问题就是获取到的大小是缩放过后的,大小不是屏幕的真正大小,接下来我们使用 EnumDisplaySettingsExW 获取
#include <Windows.h>
#include <iostream>
#include <vector>
RECT GetScreenRect(int screen) {
DISPLAY_DEVICEW device;
device.cb = sizeof(device);
BOOL result = EnumDisplayDevicesW(NULL, screen, &device, 0);
DEVMODEW device_mode;
device_mode.dmSize = sizeof(device_mode);
device_mode.dmDriverExtra = 0;
result = EnumDisplaySettingsExW(device.DeviceName, ENUM_CURRENT_SETTINGS, &device_mode, 0);
int x = device_mode.dmPosition.x;
int y = device_mode.dmPosition.y;
int width = device_mode.dmPelsWidth;
int height = device_mode.dmPelsHeight;
return { x, y, x + width, y + height };
}
int main(void) {
// 获取当前显示器的数目
int numbers = GetSystemMetrics(SM_CMONITORS);
std::cout << "numbers:" << numbers << std::endl;
for (int i = 0; i < numbers; ++i) {
auto size = GetScreenRect(i);
std::cout << "width:" << (size.right - size.left) << std::endl;
std::cout << "height:" << (size.bottom - size.top) << std::endl;
}
getchar();
return 0;
}
输出的大小符合我们实际的大小,也不用判断 dpi 的属性