0

Previously I built my program using System.Windows.Window, and I could cancel the window closing event by overriding the OnClosing event so that the window could only be closed through the tray menu. However, when I tried to use the WinUI3 template to build the program, this functiona didn't seem to work, because the template was implemented using WindowEx, which inherits Microsoft.Ui.Xaml.Window, and I really couldn't prevent the window before calling the Closing event. How can I deal with that? This is the codes of MainWindow.

public sealed partial class MainWindow : WindowEx (WindowEx : Microsoft.Ui.Xaml.Window)
{
    private readonly Microsoft.UI.Dispatching.DispatcherQueue dispatcherQueue;

    public MainWindow()
    {
        InitializeComponent();

        AppWindow.SetIcon(Path.Combine(AppContext.BaseDirectory, "Assets/WindowIcon.ico"));
        Content = null;
        Title = "AppDisplayName".GetLocalized();

        // Theme change code picked from https://github.com/microsoft/WinUI-Gallery/pull/1239
        dispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();
    }

    // this handles updating the caption button colors correctly when indows system theme is changed
    // while the app is open
    private void Settings_ColorValuesChanged(UISettings sender, object args)
    {
         This calls comes off-thread, hence we will need to dispatch it to current app's thread
        dispatcherQueue.TryEnqueue(TitleBarHelper.ApplySystemThemeToCaptionButtons);
    }
    // ovverride OnClosing ?!
}


I just want my program running in background and can only be closed through the tray menu.

Jack251970
  • 39
  • 2

1 Answers1

0

Since you have WinUIEx installed, you can use the Hide() extension method.

pubilc MainWindow()
{
    this.InitializeComponent();
    this.Closed += MainWindowClosed;
}

private void MainWindow_Closed(object sender, WindowEventArgs args)
{
    // Keep the closed event from going deeper.
    args.Handled = true;
    // Hide the current window.
    this.Hide();
}
Andrew KeepCoding
  • 7,040
  • 2
  • 14
  • 21