Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know user has clicked "X" or the "Close" button?

Tags:

c#

.net

winforms

In MSDN I found CloseReason.UserClosing to know that the user had decided to close the form but I guess it is the same for both clicking the X button or clicking the close button. So how can I differentiate between these two in my code?

Thanks all.

like image 640
Bohn Avatar asked Apr 21 '10 14:04

Bohn


People also ask

How to handle Form close event in c#?

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. To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .

How do I close an application in C#?

Exit(exitCode) function is used to terminate an entire application with the exitCode as the exit code in C#. The Environment. Exit() function terminates the entire current application and returns an exit code to the current operating system.


1 Answers

Assuming you're asking for WinForms, you may use the FormClosing() event. 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. Try to cast sender as a Button control, and verify perhaps for its name "CloseButton", for instance.

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {     if (string.Equals((sender as Button).Name, @"CloseButton"))         // Do something proper to CloseButton.     else         // Then assume that X has been clicked and act accordingly. } 

Otherwise, I have never ever needed to differentiate whether X or CloseButton was clicked, as I wanted to perform something specific on the FormClosing event, like closing all MdiChildren before closing the MDIContainerForm, or event checking for unsaved changes. Under these circumstances, we don't need, according to me, to differentiate from either buttons.

Closing by ALT+F4 will also trigger the FormClosing() event, as it sends a message to the Form that says to close. You may cancel the event by setting the

FormClosingEventArgs.Cancel = true.  

In our example, this would translate to be

e.Cancel = true. 

Notice the difference between the FormClosing() and the FormClosed() events.

FormClosing occurs when the form received the message to be closed, and verify whether it has something to do before it is closed.

FormClosed occurs when the form is actually closed, so after it is closed.

Does this help?

like image 89
Will Marcouiller Avatar answered Oct 09 '22 06:10

Will Marcouiller