Search code examples
.netmauimaui-windows

.net MAUI how to maximize application on startup


How can I make a .net MAUI app maximize the window on Windows when it's launched ? Currently it is starting as a small window and I don't want the user to have to constantly maximize it.

Thanks,


Solution

  • The maui team has to wait on the winui team to implement any missing features so they can access Windows specific attributes, but this github discussion shows some workarounds that you can plug into your MauiApp.CreateBuilder() method.

    The workaround calls the windows native services if the application is running on windows. From there you can plug in any WinUI3 methods, but that's something I'm not familiar with at all. I adopted the answer from LanceMcCarthy to maximize the window on startup or resume his set size if that presenter isn't right. Idk if the winuiAppWindow.Presenter would ever not be an OverlapPresenter, but I left it in there anyway.

    This works on my current VS2022 17.3 Preview 1 maui RC3 version, running on windows 11

    using Microsoft.Maui.LifecycleEvents;
    
    #if WINDOWS
    using Microsoft.UI;
    using Microsoft.UI.Windowing;
    using Windows.Graphics;
    #endif
    
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                });
    #if WINDOWS
            builder.ConfigureLifecycleEvents(events =>
            {
                events.AddWindows(wndLifeCycleBuilder =>
                {
                    wndLifeCycleBuilder.OnWindowCreated(window =>
                    {
                        IntPtr nativeWindowHandle = WinRT.Interop.WindowNative.GetWindowHandle(window);
                        WindowId win32WindowsId = Win32Interop.GetWindowIdFromWindow(nativeWindowHandle);
                        AppWindow winuiAppWindow = AppWindow.GetFromWindowId(win32WindowsId);
                        if(winuiAppWindow.Presenter is OverlappedPresenter p)
                            p.Maximize();
                        else
                        {
                            const int width = 1200;
                            const int height = 800;
                            winuiAppWindow.MoveAndResize(new RectInt32(1920 / 2 - width / 2, 1080 / 2 - height / 2, width, height));
                        }
                    });
                });
            });
    #endif
            return builder.Build();
        }
    }
    

    There's been a bunch of winui developments in just the couple months i've been dabbling in maui, and more planned (winui roadmap ) So chances are any major short comings will be fixed soon, especially with maui heading for general availability any day now.