0

I have an HWND window in my app, and I want to know the size of the monitor it's on. This will help me position my HWND on the monitor in some scenarios.

How can I get the resolution of the monitor for a given window/HWND in WinUI 3 and Win32 (in C++, preferrably)?

citelao
  • 4,898
  • 2
  • 22
  • 36

1 Answers1

1

Once you have an HWND for your window (for example, see Retrieve a window handle (HWND) for WinUI 3, WPF, and WinForms), you can use Win32 functions for this:

// Get the HWND, for clarity
HWND GetHwndForWindow(winrt::Window const& window)
{
    auto nativeWindow = window.try_as<::IWindowNative>();
    HWND hwnd{};
    winrt::check_hresult(nativeWindow->get_WindowHandle(&hwnd));
    return hwnd;
}

// See note below about "work area"
RECT GetMonitorWorkAreaForWindow(winrt::Window const& window)
{
    const auto hwnd = GetHwndForWindow(window);

    // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-monitorfromwindow
    const auto hmonitor = ::MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);

    // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmonitorinfoa
    MONITORINFO monitorInfo{sizeof(MONITORINFO)};
    THROW_IF_WIN32_BOOL_FALSE(GetMonitorInfo(hmonitor, &monitorInfo));
    return monitorInfo.rcWork;
}

If you're looking for usable space, you probably want the work area, and not the actual size of the monitor (rcWork, not rcMonitor). See the Taskbar#Taskbar Display Options and MONITORINFO.

See MonitorFromWindow and GetMonitorInfo.

citelao
  • 4,898
  • 2
  • 22
  • 36
  • 2
    Note that Windows might lie to you about the native resolution unless you have a manifest that says your app is DPI-aware, search "win32 high dpi" and "win32 dpi aware", for example - https://learn.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows – Dave S Apr 27 '23 at 17:22
  • 1
    About DPI concerns, you may want to look at my answer here: https://stackoverflow.com/questions/4631292/how-to-detect-the-current-screen-resolution/74035135#74035135 – gil123 Apr 29 '23 at 13:45
  • Thanks! Those links are really helpful! I might need to ask a follow-up based on that MSDN link: `it can difficult to know which API calls can return virtualized values based on the thread context; this information is not currently sufficiently documented by Microsoft`. Is there good 3rd-party documentation about this anywhere? – citelao May 01 '23 at 20:53