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

WinUI 3中如何动态设置主窗口的初始大小与位置?

WinUI 3 窗口位置与尺寸控制实现方案

WinUI 3 的 Microsoft.UI.Xaml.Window 确实没有直接暴露位置、尺寸的属性/方法,但官方提供了基于 AppWindow 的新窗口管理范式来实现这类需求,以下是针对你场景的具体实现步骤:

1. 获取目标显示器的可用工作区

方式一:获取主显示器工作区(默认方案)

通过 DisplayArea 类直接获取主显示器的可用区域(自动扣除任务栏等系统UI):

using Microsoft.UI.Windowing;
using Windows.Graphics;

// 获取主显示器的显示区域
var mainDisplayArea = DisplayArea.GetFromWindowId(WindowId.GetFromWindow(IntPtr.Zero), DisplayAreaFallback.Primary);
// 提取可用工作区
RectInt32 workArea = mainDisplayArea.WorkArea;

方式二:获取当前焦点所在显示器

如果需要定位到当前有焦点的显示器,需结合Win32 API实现(WindowAppSDK暂未提供直接API):

using System.Runtime.InteropServices;
using Microsoft.UI.Windowing;
using Windows.Graphics;

// 导入Win32 API
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);

[DllImport("user32.dll")]
private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);

// 定义MONITORINFO结构体
[StructLayout(LayoutKind.Sequential)]
private struct MONITORINFO
{
    public uint cbSize;
    public RectInt32 rcMonitor;
    public RectInt32 rcWork;
    public uint dwFlags;
}

// 获取焦点窗口所在显示器的工作区
IntPtr foregroundHwnd = GetForegroundWindow();
const uint MONITOR_DEFAULTTONEAREST = 0x00000002;
IntPtr monitorHandle = MonitorFromWindow(foregroundHwnd, MONITOR_DEFAULTTONEAREST);

MONITORINFO monitorInfo = new MONITORINFO();
monitorInfo.cbSize = (uint)Marshal.SizeOf(monitorInfo);
GetMonitorInfo(monitorHandle, ref monitorInfo);
RectInt32 workArea = monitorInfo.rcWork;

2. 设置窗口位置与尺寸

通过 AppWindow 对象(WinUI 3 窗口的底层管理对象)来控制窗口的位置和大小,推荐在应用启动阶段处理:

在 App.xaml.cs 的 OnLaunched 方法中实现

protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
    m_window = new MainWindow();
    
    // 获取目标工作区(这里用主显示器示例,可替换为方式二的workArea)
    var mainDisplayArea = DisplayArea.GetFromWindowId(WindowId.GetFromWindow(IntPtr.Zero), DisplayAreaFallback.Primary);
    RectInt32 workArea = mainDisplayArea.WorkArea;

    // 获取窗口对应的AppWindow
    AppWindow appWindow = AppWindow.GetFromWindowId(WindowId.GetFromWindow(m_window.WindowHandle));
    if (appWindow != null)
    {
        // 将窗口移动到显示器左上角,并设置为工作区尺寸
        appWindow.MoveAndResize(new RectInt32(workArea.X, workArea.Y, workArea.Width, workArea.Height));
    }
    
    m_window.Activate();
}

关键说明

  • AppWindow 是WinUI 3官方推荐的窗口管理核心对象,替代了传统WPF/UWP直接操作Window属性的模式
  • MoveAndResize 方法可一次性完成位置和尺寸的设置,RectInt32 参数对应窗口左上角坐标(X/Y)和宽高
  • 多显示器场景下,workArea.X/Y 会自动适配显示器的实际坐标(非主显示器可能不为0),保证窗口定位准确
  • 该方式创建的是普通浮动窗口,而非最大化/全屏状态,完全符合你的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 07:13:33