I'm trying to create a confirmation for when the user tries to close a form with a button, or by x
button, Alt
I'm trying to create a confirmation for when the user tries to close a form with a button, or by x
button, Alt
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);
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.
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