How can I set the window size in MAUI?
Background info: I only care about Windows for this application - I chose MAUI so I could use Blazor for a desktop application. For some reason the default window size is massive (takes up almost all of my 1440p screen space). The application I'm making only needs about 600x600. Having a way to make the window size fixed would also be helpful although I'm happy to have the app simply be responsive.
UPDATE
For .Net 8, see also jeff's answer.
Other answers are also worth looking at.
Updated for Maui GA (I'll add to that discussion too):
#if WINDOWS
using Microsoft.UI;
using Microsoft.UI.Windowing;
using Windows.Graphics;
#endif
namespace YourAppNameHere;
public partial class App : Application
{
const int WindowWidth = 400;
const int WindowHeight = 750;
public App()
{
InitializeComponent();
Microsoft.Maui.Handlers.WindowHandler.Mapper.AppendToMapping(nameof(IWindow), (handler, view) =>
{
#if WINDOWS
var mauiWindow = handler.VirtualView;
var nativeWindow = handler.PlatformView;
nativeWindow.Activate();
IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(nativeWindow);
var windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(windowHandle);
var appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
appWindow.Resize(new Windows.Graphics.SizeInt32(WindowWidth, WindowHeight));
#endif
});
MainPage = new MainPage();
}
...
OR if want to base it on requested dimensions of MainPage, before appending handler could do:
MainPage = new MainPage();
var width = (int)MainPage.WidthRequest;
var height = (int)MainPage.HeightRequest;
then use those dimensions (probably add some padding to get whole window size, because MainPage is client area).
NOTE: I was testing for Windows, so in the drop-down at upper-left of source text editor pane, I had selected ... (net6.0-windows10.0.19041.0)
. That's why I did not notice that I needed #if
around the using
s, to avoid errors on Android etc.