Jon*_*n B 129
您可以覆盖OnFormClosing来执行此操作.请注意,不要做任何太意外的事情,因为单击"X"关闭是一个很好理解的行为.
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
// Confirm user wants to close
switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing", MessageBoxButtons.YesNo))
{
case DialogResult.No:
e.Cancel = true;
break;
default:
break;
}
}
Run Code Online (Sandbox Code Playgroud)
Phi*_*ace 19
重写OnFormClosing方法.
注意: 您需要检查CloseReason并仅在UserClosing时更改行为.你不应该在这里放任何会阻碍Windows关闭程序的东西.
这是来自Windows 7徽标计划的要求.
小智 17
这些答案缺乏的一件事,以及新手们可能正在寻找的是,虽然举办活动很愉快:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// do something
}
Run Code Online (Sandbox Code Playgroud)
除非您注册该活动,否则它根本不会做任何事情.把它放在类构造函数中:
this.FormClosing += Form1_FormClosing;
Run Code Online (Sandbox Code Playgroud)
Cha*_*hap 10
重写OnFormClosing或注册事件FormClosing.
这是在派生形式中覆盖OnFormClosing函数的示例:
protected override void OnFormClosing(FormClosingEventArgs e)
{
e.Cancel = true;
}
Run Code Online (Sandbox Code Playgroud)
这是阻止表单关闭的事件处理程序的一个示例,它可以在任何类中:
private void FormClosing(object sender,FormClosingEventArgs e)
{
e.Cancel = true;
}
Run Code Online (Sandbox Code Playgroud)
要获得更高级的功能,请检查FormClosingEventArgs上的CloseReason属性以确保执行适当的操作.如果用户尝试关闭表单,您可能只想执行备用操作.
正如Jon B所说,但你也想检查ApplicationExitCall
和TaskManagerClosing
CloseReason:
protected override void OnFormClosing(FormClosingEventArgs e)
{
if ( e.CloseReason == CloseReason.WindowsShutDown
||e.CloseReason == CloseReason.ApplicationExitCall
||e.CloseReason == CloseReason.TaskManagerClosing) {
return;
}
e.Cancel = true;
//assuming you want the close-button to only hide the form,
//and are overriding the form's OnFormClosing method:
this.Hide();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
129085 次 |
最近记录: |