Home > database >  How do I show a MessageBox promp when the user has clicked the X button in WPF
How do I show a MessageBox promp when the user has clicked the X button in WPF

Time:03-09

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.

CodePudding user response:

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.

CodePudding user response:

Your code is working properly.

You have to add OnClosing event to the window,

And when you click on close of the window you will see the message

<Window x:Class="TestProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestProject"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800"

    Closing="MainWindow_OnClosing">
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void MainWindow_OnClosing(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();
        }
    }
}
  • Related