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

如何将MAUI应用窗口设为固定不可调整或设置最小宽高?

MAUI Windows窗口固定大小与最小宽高配置方案

一、固定窗口大小(禁止用户调整)

MAUI跨层API未提供直接禁用窗口调整的选项,需通过Windows平台特定代码实现:

  • 打开Windows项目下的App.xaml.cs,在OnLaunched方法中添加窗口样式修改逻辑:
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    base.OnLaunched(args);

    var currentWindow = Application.Current.Windows.FirstOrDefault();
    if (currentWindow == null) return;

    var nativeWindow = currentWindow.Handler.PlatformView as Microsoft.UI.Xaml.Window;
    IntPtr hwnd = WinRT.Interop.WindowNative.GetWindowHandle(nativeWindow);
    
    // 获取并修改窗口样式,移除可调整大小及最大化按钮
    int windowStyle = Win32.User32.GetWindowLong(hwnd, Win32.User32.GWL_STYLE);
    windowStyle &= ~Win32.User32.WS_THICKFRAME; // 移除可拖动调整大小的边框
    windowStyle &= ~Win32.User32.WS_MAXIMIZEBOX; // 移除最大化按钮(可选)
    Win32.User32.SetWindowLong(hwnd, Win32.User32.GWL_STYLE, windowStyle);

    // 设置固定宽高
    currentWindow.Width = 800;
    currentWindow.Height = 600;
}
  • 在Windows项目中创建Win32.cs类,定义所需的Win32 API:
internal static class Win32
{
    internal static class User32
    {
        public const int GWL_STYLE = -16;
        public const int WS_THICKFRAME = 0x00040000;
        public const int WS_MAXIMIZEBOX = 0x00010000;

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern int GetWindowLong(IntPtr hwnd, int index);

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern int SetWindowLong(IntPtr hwnd, int index, int style);
    }
}

完成后,窗口将保持指定大小,用户无法拖动边缘调整或点击最大化按钮。

二、设置窗口最小宽度与高度

MAUI提供原生API直接配置,无需平台特定代码,两种实现方式:

方式1:全局启动时设置

在项目根目录的App.xaml.cs中,于OnStart方法内配置:

protected override void OnStart()
{
    base.OnStart();
    var mainWindow = Application.Current.MainPage.Window;
    // 设置最小宽高
    mainWindow.MinimumWidth = 600;
    mainWindow.MinimumHeight = 400;
    // 可选:设置默认窗口尺寸
    mainWindow.Width = 800;
    mainWindow.Height = 600;
}

方式2:页面级设置

在目标页面的构造函数中配置当前窗口的最小尺寸:

public MainPage()
{
    InitializeComponent();
    // 限制当前窗口的最小宽高
    this.Window.MinimumWidth = 600;
    this.Window.MinimumHeight = 400;
}

配置后,用户可调整窗口大小,但无法缩小至指定的最小尺寸以下。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:15:41