Samarth Agarwal
Samarth Agarwal

Reputation: 2134

WPF Cancel Button

I am working on a WPF Application. One of my Windows has a Button called "Cancel" with its IsCancel=true. I need to show a message box with Yes/No when the user clicks Cancel or presses ESCAPE Key. If the user click Yes, the Window should continue closing but if the user clicks No, it should not close the form but continue the regular operation with the Window opened. How can I do so? Please help. Thanks in advance.

Upvotes: 3

Views: 7184

Answers (4)

Chamika Sandamal
Chamika Sandamal

Reputation: 24302

this will help you

void Window_Closing(object sender, CancelEventArgs e)
{
     MessageBoxResult result = MessageBox.Show(
            "msg", 
            "title", 
            MessageBoxButton.YesNo, 
            MessageBoxImage.Warning);
        if (result == MessageBoxResult.No)
        {
            // If user doesn't want to close, cancel closure
            e.Cancel = true;
        }        
}

Upvotes: 4

Hjalmar Z
Hjalmar Z

Reputation: 1601

Open a messagebox and read the result like so:

DialogResult result = MessageBox.Show(
    "Text", 
    "Title", 
    MessageBoxButtons.YesNo,
    MessageBoxIcon.Question);

if (result == DialogResult.Yes)
{
    //The user clicked 'Yes'
}
else if (result == DialogResult.No)
{
    //The user clicked 'No'
}
else
{
    //If the user somehow didn't click 'Yes' or 'No'
}

Upvotes: 1

Akshay Joy
Akshay Joy

Reputation: 1765

  var Ok = MessageBox.Show("Are you want to Close", "WPF Application", MessageBoxButton.YesNo, MessageBoxImage.Information);

            if (Ok == MessageBoxResult.Yes)
            {
                this.Close();
            }
            else
            {

            }

Upvotes: 1

JleruOHeP
JleruOHeP

Reputation: 10376

You can handle it in WindowClosing enent.

Take a look here. There is an example very close to yours.

Upvotes: 3

Related Questions