2
I’m trying to create a confirmation for when the user tries to close a form either with a button, or by the button x
, or Alt+F4, or right-click at the top and then click close, etc...
I tried to use the code below but it didn’t work:
private void Form1_FormClosing(object sender, FormClosedEventArgs 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)
{
Application.Exit();
}
}
}
It didn’t work, it’s like this code doesn’t exist, it just closes.
– ptkato
@Patrick should work, unless that form of yours isn’t leading. Is the main ?
– Zuul
And is event being triggered? Does the message appear? Also see that the if test is with != and no more ==
– iuristona
It is the main form, tested with == and with != , none worked.
– ptkato
So the error message appears or nothing appears? If it doesn’t, the problem is that you simply added the method that should receive the event, but you didn’t attach the event to the form, which should have this code snippet in the Initializecomponents() method inside the Form1.Cs file.:
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
– iuristona
@iuristona Add the content of this last comment to your reply to be complete. ;)
– Zuul
@Zuul thought about it, but there were 2 problems and the second I kicked, it does not appear in the question, it is assumed that the event is already tied to the form. Already the code as it was actually asked did not work, it was missing e.Cancel = true
– iuristona
@iuristona What I thought was adding you like: "Important Note: If the problem is the fact that the message does not even appear, it is because XXX and you should XXX." So future visitors with the same problem already know that if it appears have to cancel the event, but if the message does not appear it is because you have to attach the event to the form. (But of course, it’s up to you) :)
– Zuul
This method is not suitable for closure buttons created by the programmer, right?
– ptkato
If you are having problems try to remove this
if (e.CloseReason == CloseReason.UserClosing)
– iuristona