When closing form, FormClosed event occurs, and I want to put some work when FormClosed event occurs like:
this.FormClosed += (s, e) => {
var result = MessageBox.Show("Exit Program?", "Exit?", MessageBoxButtons.YesNo, MessageBoxIcons.Question);
if (result == DialogResult.No) {
return;
} else {
// Do some work such as closing connection with sqlite3 DB
Application.Exit();
}
};
The problem is that no matter I choose yes or no in the messagebox, the program gets closed. I need to abort program exit if I choose no, so how do I do that?
The FormClosing (as opposed to your FormClosed) event's FormClosingEventArgs contains a Cancel boolean that you can change to true. Note that this will occur even if you close the form programmatically.
this.FormClosing += (s, e) => {
var result = MessageBox.Show("Exit Program?", "Exit?", MessageBoxButtons.YesNo, MessageBoxIcons.Question);
if (result == DialogResult.No) {
e.Cancel = true;
} else {
// Do some work such as closing connection with sqlite3 DB
Application.Exit();
}
};
To determine how the form was closed, it also includes a CloseReason.
See docs here and here.
You can't use the FormClosed event, you need to use the FormClosing event and set e.Cancel to true.
The reason for that is that the FormClosed event occurs after the form has been closed, while the FormClosing event occurs as the form is being closed.
The FormClosingEventArgs class contains a boolean property called Cancel that you can set to true to stop the form from being closed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With