Reputation: 484
In windows form native application we can prevent a user to close the application when they press "X" button in the top right. the below code is an example code when the user tries to close the application, instead of closing the application will be minimized mode:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.WindowState = FormWindowState.Minimized;
}
How to achieve that on .NET MAUI?
I tried an ovveride method like OnDisappearing but no luck
Upvotes: 0
Views: 1015
Reputation: 14574
You can using the following code in the OnHandlerChanged method of the MainPage.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;
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);
window.Closed += (o, e) =>
{
e.Handled = true;
// this line will cancel the closed event
(appWindow.Presenter as Microsoft.UI.Windowing.OverlappedPresenter).Minimize();
// this line will minimize the window
};
#endif
}
Upvotes: 1