If the user wants to exit the application by clicking on the exit icon or by ALT+F4, I'd like to make a dialog box questioning the user if he/she is really sure about exiting.
How do I capture this event before the application is actually closed?
The Closing event occurs as the form is being closed. When a form is closed, all resources created within the object are released and the form is disposed. If you cancel this event, the form remains opened.
The event FormClosing() is triggered any time a form is to get closed. To detect if the user clicked either X or your CloseButton, you may get it through the sender object.
Although by default, when a form is instantiated and launched, the user does not move it, yet this event is triggered before the Load event occurs. Load: This event occurs before a form is displayed for the first time. VisibleChanged: This event occurs when the Visible property value changes.
You should subscribe to the Form_Closing event
Post a dialog box there, and if user abort the closing set the FormCloseEventArgs.Cancel to true.
For example in the Form_Load or using the designer, subscribe the event
Form1.FormClosing += new FormClosingEventHandler(Form1_Closing);
....
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
DialogResult d = MessageBox.Show("Confirm closing", "AppTitle", MessageBoxButtons.YesNo );
if(d == DialogResult.No)
e.Cancel = true;
}
Depending on the situation is not always a good thing to annoy the user with this kind of processing.
If you have valuable modified data and don't want the risk to loose the changes, then it is always a good thing to do, but if you use this only as a confirm of the close action then it's better to do nothing.
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