This article shows you how to set a window size for a MAUI app on Windows.
This is super useful for debugging – in my case, I wanted to retain a fast development cycle with lightweight debugging to work on my code quickly, but still see everything in roughly the right aspect ratio for my typical end-user device – an Android smartphone. But using the emulator for this was not usable, as it’s comparably slow.
And of course the same solution will work for production use cases.
Problem
By default, you can of course change your application window’s size, but since the size is not retained between debugging runs (or at least I haven’t found a way to make it stick!), testing layout changes is still a little bit cumbersome as some changes require your app to be rebuilt, and you’d always have to manually resize your application window again.
It’d be more convenient, if the change actually would stay between runs – but we can always just set the window size on startup using MAUI handlers!
Solution
This code should work for MAUI on .NET 7, with Visual Studio 17.4 (on Windows, in case that wasn’t kind of obvious).
In your App.xaml.cs -file, you should have a public constructor called App(). In the method, after InitializeComponent(), add a WindowHandler (MAUI supports using Handlers to customize platform-specific UI components) with the following contents:
public App()
{
InitializeComponent();
Microsoft.Maui.Handlers.WindowHandler.Mapper.AppendToMapping(nameof(IWindow), (handler, view) =>
{
#if WINDOWS && DEBUG
var mauiWindow = handler.VirtualView;
var nativeWindow = handler.PlatformView;
nativeWindow.Activate();
IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(nativeWindow);
WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(windowHandle);
AppWindow appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
appWindow.Resize(new SizeInt32(300, 600));
#endif
});
MainPage = new MainPage();
}
Alternatively, you can of course change your call to appWindow.Resize to use some variables – maybe even calculate the size based on the actual screen size, available in:
Microsoft.Maui.Devices.DeviceDisplay.MainDisplayInfo
… and that’s it. Should be enough to change your window size on Windows :)
References
- https://stackoverflow.com/questions/72399551/maui-net-set-window-size
- https://learn.microsoft.com/en-us/dotnet/maui/user-interface/handlers/customize?view=net-maui-7.0
- “Performing cleanup” – Excel is stuck with an old, conflicted file and will never recover. - November 12, 2024
- How to add multiple app URIs for your Entra app registration? - November 5, 2024
- How to access Environment Secrets with GitHub Actions? - October 29, 2024