Assuming you are requesting WinForms, you can use the FormClosing () event . The FormClosing () event is fired at any time when the form closes.
To determine if user X clicked or your CloseButton, you can get it through the sender object. Try sending the sender as a Button control and maybe check, for example, its name "CloseButton".
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (string.Equals((sender as Button).Name, @"CloseButton"))
Otherwise, I never needed to distinguish whether X or CloseButton was pressed, because I wanted to do something specific in the FormClosing event, for example, close all MdiChildren before closing MDIContainerForm or checking events for unsaved changes. In these conditions, we do not need, in my opinion, to distinguish from both buttons.
Closing ALT + F4 also raises the FormClosing () event because it sends a message to the form that says close. You can cancel the event by setting
FormClosingEventArgs.Cancel = true.
In our example, this will mean
e.Cancel = true.
Note the difference between the FormClosing () and FormClosed () events.
FormClosing occurs when a form receives a message to close and checks to see if it has something to do before closing.
FormClosed occurs when the form is actually closed, therefore, after it is closed.
Does it help?
Will Marcouiller Apr 21 '10 at 14:20 2010-04-21 14:20
source share