Home > database >  How to keep a window open on Window.Closing Event C#
How to keep a window open on Window.Closing Event C#

Time:03-09

I want to know if there is a way to keep a window open even after pressing X. It will be a warning of sorts. When i press X on the main window the message box will apear with the error and when i press ok i want to return to the main window.

private void Window_Closed(object sender, EventArgs a)
  {
     MessageBox.Show("Hello", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
  }
  private void Window_Closing(object sender, CancelEventArgs e)
  {
     e.Cancel = true;
  }

There is a way to do that ? I am sorry for the bad explanation

CodePudding user response:

Solution 1 which you wanted:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
     MessageBoxResult closingMessegeBoxResult = MessageBox.Show("Is it OK to close?", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
     if (closingMessegeBoxResult != MessageBoxResult.OK)
     {
         e.Cancel = true;
     }
}

Here is the Graphical result of it :

Screen shot of result...

Solution 2 which is for Pro WPF developers:

is making your WindowStyle=" None" on Xaml and making your own closing minimizing and maximizing buttons with a StackPanel few buttons and a mouse down button event for stack panel (for moving the window) which is linked to this handler :

  private void WindowStartedMoving(object sender, MouseButtonEventArgs e)
  {
     DragMove();
  }

please ask me if you had any more questions :)

  • Related