当窗口关闭时,它会引发两个事件:Closing 和 Closed。
Closing 在窗口关闭之前引发,它提供一种机制,可以通过这种机制来阻止窗口关闭。 系统会向Closing 事件处理程序传递一个 FormClosingEventArgs e,该参数实现 Boolean Cancel 属性,将该属性设置为 true 可以阻止窗口关闭。
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("确定要退出本系统吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
this.Dispose();
Application.Exit();
}
else
{
e.Cancel = true; //不关闭窗口 //关闭窗口 e.Cancel = false;
}
}
如果未处理Closing,或者处理但未取消,则窗口将关闭。 在窗口真正关闭之前,会引发 Closed,这时无法阻止窗口关闭。