Reputation: 167
I'm working on a .NET MAUI app which I'd like to deploy on Windows beside Android.
My goal is to specify a minimal window width and a minimal window height only
affecting Windows as a platform.
My attempt to set the aforementioned properties inside App.xamls.cs
:
public App()
{
InitializeComponent();
Microsoft.Maui.Handlers.WindowHandler.WindowMapper[nameof(IWindow)] = (handler, view) =>
{
#if WINDOWS
var nativeWindow = handler.NativeView;
nativeWindow.Activate();
IntPtr windowHandle = PInvoke.User32.GetActiveWindow();
PInvoke.User32.SetWindowPos(windowHandle,
PInvoke.User32.SpecialWindowHandles.HWND_TOP,
0, 0, width, height, // width and height are ints
PInvoke.User32.SetWindowPosFlags.SWP_NOMOVE);
#endif
};
}
Unfortunately, it does not work as I'm receiveing the following error:
Error CS0117 'WindowHandler' does not contain a definition for 'WindowMapper
Any help is greatly appreciated!
Upvotes: 0
Views: 3339
Reputation: 14519
If you want to specify a minimal window width and a minimal window height only, you can make the project's target framwork as .net 7.0. And then override the App's CreateWindow method:
protected override Window CreateWindow(IActivationState activationState)
{
var window = base.CreateWindow(activationState);
window.MinimumHeight = 600; // set minimal window height
window.MinimumWidth = 800; // set minimal window width
return window;
}
And you can also use the handler to resize the window. In the page.cs:
protected override void OnHandlerChanged()
{
base.OnHandlerChanged();
#if WINDOWS
Microsoft.UI.Xaml.Window? window = (Microsoft.UI.Xaml.Window?)(App.Current?.Windows.First<Window>().Handler.PlatformView);
if(window == null){
return;
}
IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(window);
Microsoft.UI.WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(windowHandle);
Microsoft.UI.Windowing.AppWindow appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
appWindow.Resize(new Windows.Graphics.SizeInt32(800,600));
#endif
}
Upvotes: 3
Reputation: 11
You could take advantage of .NET MAUI support for partial classes to avoid the usage of the #if WINDOWS
preprocessor directive.
Here is an idea with a partial method that is only implemented in Window
Note: App.cs
Windows file should have the same namespace as the platform independent App.cs
In App\App.xaml.cs
namespace App;
public partial class App : Application
{
public App()
{
InitializeComponent();
}
protected override Window CreateWindow(IActivationState activationState)
{
var window = new Window(new AppShell());
UpdateWindow(window);
return window;
}
partial void UpdateWindow(Window window);
}
In App\Platforms\Windows\App.cs
namespace App
{
public partial class App : Application
{
partial void UpdateWindow(Window window)
{
window.MinimumWidth = 800;
window.MinimumHeight = 600;
window.Width = 1024;
window.Height = 800;
}
}
}
Upvotes: 1