How to disable screen closure via X at top

Nigel 271 Reputation points
2023-05-28T09:05:00.0533333+00:00

So, I have a WPF/Blazor hybrid with a second window for information. If the second window is closed off with the X in the top corner, it leaves the program hanging in the background, which is not good for system resources. In order to ensure that the user closes the window with the home button, how do I disable use of the X in the top right without having to close the whole application as in the following code snippet?

 public partial class AboutWin : Window
    {
        public AboutWin()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MainWindow mainWindow = new MainWindow();
            mainWindow.Show();
            this.Hide();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Application.Current.Shutdown();
        }
    }

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,374 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 31,971 Reputation points Microsoft Vendor
    2023-05-29T02:56:26.83+00:00

    Hi @Nigel , Welcome to Microsoft Q&A.

    Your idea is totally doable.

    Just add it to the Closing event.

    Then call the Hide() method to hide the currently closed window//whatever you want to do.

       public AboutWin()
        {
            InitializeComponent();
            Closing += AboutWin_Closing; // Attach event handler
        }
    
        private void AboutWin_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true; // Cancel the closing event
            Hide(); // Hide the window instead of closing it
        }
    

    This method is fully applicable to Winfrom or Wpf.

    If it does not work in WPF/Blazor, please comment bellow.

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful