c++windowswinapiwinui-3multiple-monitors

How can I get the size of the monitor that my current window is on in WinUI 3 and Win32?


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)?


Solution

  • 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.