I need a C++ winAPI function to get selected display current resolution
- User
I need a C++ winAPI function to get selected display current resolution
- Assistant
You can use the following code to get the current resolution of the selected display using C++ and WinAPI:
#include <Windows.h> void GetSelectedDisplayResolution(int& width, int& height) { // Get the handle of the monitor on which the current window is displayed HMONITOR hMonitor = MonitorFromWindow(GetForegroundWindow(), MONITOR_DEFAULTTONEAREST); // Get the display device corresponding to the monitor handle DISPLAY_DEVICE displayDevice = { 0 }; displayDevice.cb = sizeof(DISPLAY_DEVICE); EnumDisplayDevices(NULL, 0, &displayDevice, 0); EnumDisplayDevices(displayDevice.DeviceName, 0, &displayDevice, 0); // Get the display settings corresponding to the display device DEVMODE devMode = { 0 }; devMode.dmSize = sizeof(DEVMODE); EnumDisplaySettings(displayDevice.DeviceName, ENUM_CURRENT_SETTINGS, &devMode); // Get the current resolution of the selected display width = devMode.dmPelsWidth; height = devMode.dmPelsHeight; }You can call this function as follows:
- User
You was not use hMonitor
- Assistant
You're right, I apologize for the mistake in my previous response. Here's a modified version of the function that uses the
hMonitorhandle to get the resolution of the selected display:#include <Windows.h> void GetSelectedDisplayResolution(int& width, int& height) { // Get the handle of the monitor on which the current window is displayed HMONITOR hMonitor = MonitorFromWindow(GetForegroundWindow(), MONITOR_DEFAULTTONEAREST); // Get the display settings corresponding to the selected monitor MONITORINFOEX monitorInfo = { 0 }; monitorInfo.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(hMonitor, &monitorInfo); DEVMODE devMode = { 0 }; devMode.dmSize = sizeof(DEVMODE); EnumDisplaySettings(monitorInfo.szDevice, ENUM_CURRENT_SETTINGS, &devMode); // Get the current resolution of the selected display width = devMode.dmPelsWidth; height = devMode.dmPelsHeight; }You can call this function as follows:
int main() { int width, height; GetSelectedDisplayResolution(width, height); printf("Selected display resolution: %dx%d\n", width, height); return 0; }