I开发者_如何学运维n a windows form project in C#/.net/Visual Studio 2010, if someone hits the close window button, I want to disable some other things in the program as a consequence. Is there a method call for hitting "X" that I can extend?
The two events that you should use are FormClosing
and FormClosed
.
In the .Net Framework verion 2.0 these events replaced the obsolete Closing
and Closed
events.
The reason for the new events was that the old ones were not raised when the Application.Exit
method was called.
An example of the usage of the FormClosing
event is below:
public Form1()
{
InitializeComponent();
this.FormClosing += Form1_FormClosing;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult result = MessageBox.Show("Really close this form?", string.Empty, MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
e.Cancel = true;
}
}
That code simply asks the user if they want to close the form, and if No is selected, it then cancels the event. You can put any logic you require in the event handler.
The MSDN article on Form.Closing
is here and includes references about why the event was made obsolete. The reference for Form.FormClosing
is here
Your window class publishes two events for this purpose:
Closing allows you to cancel the close if it's inappropriate
Closed allows you to react on close.
Just register a handler on the FormClosed event.
精彩评论