Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch the event of exiting a Winforms application?

Tags:

c#

.net

winforms

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?

like image 515
l46kok Avatar asked Jun 15 '12 08:06

l46kok


People also ask

Which event that has happen when you close your form?

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.

Which event value is passed when close button in the window is triggered?

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.

What is the default event of Windows Form?

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.


1 Answers

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.

like image 171
Steve Avatar answered Oct 06 '22 01:10

Steve