简体   繁体   中英

C# Windows Forms Application Closing

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 
       }
   } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM