[SOLVED] How do I show a MessageBox promp when the user has clicked the X button in WPF

Issue

I am working on a C# WPF application.
After i get some input from the user i need to check some conditions and if the condition don’t match and the user has pressed the X button I need to be able to show a MessageBox containing an error. After the user has pressed ok in the MessageBox i need the user to return to the previous window.
My code looks something like this.

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

  }

For now i only want to be able to show the MessageBox with a random error.

Solution

You should use the MessageBoxButton.OKCancel option to enable the user to avoid closing the window:

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

Using the above code, the window will only be closed when the user clicks the "OK" button of the dialog.

Answered By – mm8

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *