如何在.NET MAUI macOS(net6.0-maccatalyst)中设置启动页大小
.NET MAUI macOS平台设置启动窗口大小实现方案
对应Windows平台已成熟的启动窗口大小设置逻辑,macOS平台可通过原生生命周期钩子修改底层NSWindow属性实现,无第三方依赖,启动无闪烁,是目前稳定性最高的实现方式。
具体实现步骤
- 第一步:在项目
MauiProgram.cs中注册MacCatalyst平台生命周期回调,在窗口初始化完成时设置尺寸
using Microsoft.Maui.LifecycleEvents; using CoreGraphics; namespace YourMauiApp; public static class MauiProgram { public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); }) .ConfigureLifecycleEvents(events => { events.AddiOS(iosLifecycle => { iosLifecycle.FinishedLaunching((app, launchOptions) => { // 仅在Mac Catalyst/macOS平台执行配置 if (DeviceInfo.Current.Platform == DevicePlatform.MacCatalyst) { var firstUiWindow = app.Windows.FirstOrDefault(); if (firstUiWindow != null) { var nsWindow = firstUiWindow.GetNSWindow(); if (nsWindow != null) { // 自定义窗口尺寸:宽1200、高800 nsWindow.SetFrame(new CGRect(0, 0, 1200, 800), display: true, animate: false); // 窗口居中显示 nsWindow.Center(); // 可选:设置窗口最小允许尺寸 nsWindow.MinSize = new CGSize(800, 600); } } } return true; }); }); }); return builder.Build(); } }
- 第二步:添加UIWindow扩展方法,用于获取底层原生NSWindow实例,注意加条件编译避免其他平台编译报错
using UIKit; using ObjCRuntime; #if MACCATALYST using AppKit; #endif namespace YourMauiApp; public static class UIWindowExtensions { #if MACCATALYST public static NSWindow? GetNSWindow(this UIWindow uiWindow) { if (uiWindow.RespondsToSelector(new Selector("window"))) { IntPtr nsWindowPtr = Messaging.ObjCMessaging.IntPtr_objc_msgSend( uiWindow.Handle, Selector.GetHandle("window") ); return Runtime.GetNSObject<NSWindow>(nsWindowPtr); } return null; } #endif }
注意事项
- macOS坐标系原点在屏幕左下角,如果需要自定义窗口起始位置,计算Y坐标时要用屏幕可见区域高度减去窗口高度,和Windows坐标系逻辑相反
- 如果需要禁止用户调整窗口大小,可在拿到nsWindow实例后添加代码:
nsWindow.StyleMask &= ~NSWindowStyle.Resizable; - 如果需要窗口默认最大化,可以替换SetFrame逻辑,直接设置
nsWindow.IsZoomed = true; - 该方案在.NET 6/7/8版本的MAUI上均验证可用,不会出现启动时先显示默认尺寸窗口再跳转到自定义尺寸的闪烁问题
内容的提问来源于stack exchange,提问作者Aleksandr
相关产品推荐
相关产品推荐

