问题描述:

I making a C# Windows Forms Application. I'm trying to have a message box popup when the "X" or Close Button is pressed to exist out of the application. This is what I have so far, and I don't know whats wrong with it. When I run the message box doesn't show up when I click on the Close Button. Any help would be appreciated. Thanks.

private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)

{

if (this.DialogResult == DialogResult.Cancel)

{

if (MessageBox.Show("Do you want to save changes to the data?",

"MktAuthorizationData",

MessageBoxButtons.YesNo) == DialogResult.Yes)

{

e.Cancel = true;

// Do Something

}

}

}

网友答案:

You need to remove below condition

if (this.DialogResult == DialogResult.Cancel)

The below code should work

private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Do you want to save changes to the data?",
                        "MktAuthorizationData", 
                        MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
            e.Cancel = true;
            // Do Something 
    }
}

In case you haven't subscribed to the event you need to do this by having this after InitializeComponent();

this.FormClosing += MainWindow_FormClosing;
网友答案:

You can add a Button Close event to close your window form with message box.

private void btnClose_Click(object sender, EventArgs e)
    {        

   if (MessageBox.Show("Do you want to save changes to the data?",
                    "MktAuthorizationData", 
                    MessageBoxButtons.YesNo) == DialogResult.Yes)
       {
        e.Cancel = true;
        // Do Something 
       }
   } 
相关阅读:
Top