UPDATE
For .Net 7, 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 = 300;
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);
WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(windowHandle);
AppWindow appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
appWindow.Resize(new 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.