Confirmation of form closure

2

I'm trying to create a confirmation for when the user tries to close a form with a button, or by x button, Alt

asked by anonymous 03.03.2014 / 17:07

3 answers

4

When arriving at the event FormClosing the Form will be closed, except if we set true to the Cancel property of the event.

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.UserClosing)
        {
            var result = MessageBox.Show(this, "Você tem certeza que deseja sair?", "Confirmação", MessageBoxButtons.YesNo);
            if (result != DialogResult.Yes)
            {
                e.Cancel = true;
            }
        }
    }

Note: If the confirmation message is not being displayed, it may be the case that the event is not triggered because it is not attached to the form. In this case, confirm that the InitializeComponents() method inside the Form1.Designer.cs file contains the code snippet:

this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);

    
03.03.2014 / 17:29
0

My code looks like this on the main Form:

        private void Form1_FormClosing(object sender, FormClosingEventArgs e){
        var result = MessageBox.Show("Deseja realmente sair?", "Rei dos Pisos", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);            
            if (Convert.ToString(result) == "Cancel") { e.Cancel = true; }            
    }

At least it works when I click the close button on the form.

    
20.01.2016 / 19:46
-1
     var result = MessageBox.Show("Deseja realmente sair?", "Rei dos Pisos", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);            
            if (Convert.ToString(result) == "Cancel")
 { 
    e.Cancel = true; 
 } else{Aplication.Exit();// faltou só isso
    
08.11.2017 / 01:55