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

如何设置.NET MAUI Windows Machine目标的启动窗口尺寸?

配置.NET MAUI Windows应用启动窗口固定尺寸

方式一:通过launchSettings.json配置

你猜测的方向是对的,可以在launchSettings.json的Windows Machine配置中添加启动参数指定窗口尺寸。具体操作如下:

找到项目根目录下的Properties/launchSettings.json,定位到profiles下的Windows Machine节点,添加commandLineArgs字段,使用--window-size参数(宽高用逗号分隔,无空格):

"profiles": {
  "Windows Machine": {
    "commandName": "MsixPackage",
    "nativeDebugging": true,
    "commandLineArgs": "--window-size 800,600"
  }
}

注意:这个方法仅在调试阶段生效,打包后的正式应用不会读取该配置。

方式二:通过代码设置(全局生效)

如果launchSettings的配置无法满足需求(比如打包后仍需固定尺寸),可以直接在代码中设置窗口尺寸,这是更可靠的全局方案:

方法1:在CreateWindow中设置(跨平台兼容)

修改项目根目录下的App.xaml.cs,重写CreateWindow方法:

protected override Window CreateWindow(IActivationState activationState)
{
    var window = base.CreateWindow(activationState);
    // 仅针对Windows平台生效,避免影响其他平台
#if WINDOWS
    window.Width = 800;
    window.Height = 600;
    // 可选:设置窗口居中显示
    var display = DisplayInfo.Current;
    window.X = (display.Width - window.Width) / 2;
    window.Y = (display.Height - window.Height) / 2;
#endif
    return window;
}

方法2:在Windows平台专属代码中设置

修改Platforms/Windows/App.xaml.cs的OnLaunched方法:

protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    base.OnLaunched(args);

    var mainWindow = Application.Current.Windows[0];
    if (mainWindow != null)
    {
        mainWindow.Width = 800;
        mainWindow.Height = 600;
    }
}

额外补充:保存手动调整的窗口尺寸

如果希望应用记住用户手动调整后的窗口尺寸,可以借助Preferences存储尺寸数据,启动时读取并设置:

protected override Window CreateWindow(IActivationState activationState)
{
    var window = base.CreateWindow(activationState);
#if WINDOWS
    // 读取上次保存的尺寸,没有则用默认值
    var defaultWidth = 800;
    var defaultHeight = 600;
    window.Width = Preferences.Get("WindowWidth", defaultWidth);
    window.Height = Preferences.Get("WindowHeight", defaultHeight);

    // 监听窗口尺寸变化,保存到Preferences
    window.SizeChanged += (s, e) =>
    {
        Preferences.Set("WindowWidth", window.Width);
        Preferences.Set("WindowHeight", window.Height);
    };
#endif
    return window;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:33:29