You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WinUI 3与Win32(C++)中获取窗口所在显示器的尺寸

获取指定HWND窗口所在显示器的分辨率(Win32 C++ & WinUI 3)

Win32 C++ 实现

要获取HWND对应的显示器分辨率,核心是通过Windows API找到窗口所属的显示器,再读取其尺寸信息:

  1. 使用MonitorFromWindow获取窗口关联的显示器句柄HMONITOR
  2. 通过GetMonitorInfo获取显示器的详细尺寸(含完整屏幕和工作区)

代码示例

#include <Windows.h>
#include <string>

// 获取指定HWND对应的显示器分辨率
void GetMonitorResolution(HWND hWnd) {
    // 获取窗口所属显示器,若窗口不在任何显示器内则返回最近的显示器
    HMONITOR hMonitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST);
    
    MONITORINFO monitorInfo{};
    monitorInfo.cbSize = sizeof(MONITORINFO);
    
    if (GetMonitorInfo(hMonitor, &monitorInfo)) {
        // 完整显示器分辨率(物理像素)
        int fullWidth = monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left;
        int fullHeight = monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top;
        
        // 工作区分辨率(不含任务栏、停靠窗口等)
        int workWidth = monitorInfo.rcWork.right - monitorInfo.rcWork.left;
        int workHeight = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top;
        
        // 按需使用尺寸值,示例为输出调试信息
        OutputDebugStringA(("Full Screen: " + std::to_string(fullWidth) + "x" + std::to_string(fullHeight) + "\n").c_str());
        OutputDebugStringA(("Work Area: " + std::to_string(workWidth) + "x" + std::to_string(workHeight) + "\n").c_str());
    }
}

参数说明

  • MONITOR_DEFAULTTONEAREST:窗口不在任何显示器范围内时,返回最近的显示器
  • 若需严格获取包含窗口的显示器(找不到则返回NULL),可替换为MONITOR_DEFAULTTONULL

WinUI 3 实现

WinUI 3底层依赖Win32,因此可以先获取窗口对应的HWND,再复用Win32的API逻辑:

桌面版WinUI 3 获取HWND

#include <winrt/Microsoft.UI.Xaml.h>
#include <Windows.h>

using namespace winrt;
using namespace Microsoft::UI::Xaml;

void GetWinUI3WindowMonitorResolution(Window const& window) {
    // 获取WinUI3窗口的HWND
    HWND hWnd = reinterpret_cast<HWND>(window.AppWindow().Id().Value);
    
    // 复用Win32的显示器分辨率获取逻辑
    HMONITOR hMonitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST);
    
    MONITORINFO monitorInfo{};
    monitorInfo.cbSize = sizeof(MONITORINFO);
    
    if (GetMonitorInfo(hMonitor, &monitorInfo)) {
        int fullWidth = monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left;
        int fullHeight = monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top;
        // 后续可将尺寸用于窗口定位等操作
    }
}

UWP模式WinUI 3 获取HWND

若使用UWP模式的WinUI 3,需通过WindowNative接口获取HWND:

#include <winrt/Microsoft.UI.Xaml.Interop.h>

void GetUWPModeWinUI3MonitorResolution(Window const& window) {
    HWND hWnd = nullptr;
    winrt::check_hresult(winrt::get_self<::Microsoft::UI::Xaml::WindowNative>(window)->get_WindowHandle(&hWnd));
    
    // 后续逻辑同上
}

关键注意事项

  • 高DPI适配:需确保应用启用DPI感知,否则获取的可能是缩放后的逻辑像素。可在应用清单中添加:
    <dpiAwareness>PerMonitorV2</dpiAwareness>
    
  • 若窗口跨多个显示器,MonitorFromWindow会返回包含窗口重心的显示器。

内容的提问来源于stack exchange,提问作者citelao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 16:02:13