覆盖Windows窗体中的标准关闭(X)按钮

Ale*_*x S 72 c# winforms

如何更改用户单击Windows窗体应用程序中的关闭(红色X)按钮(在C#中)时发生的情况?

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)

  • @Jon B - 你应该检查一下原因.如果Windows正在关闭,您不希望显示消息框. (4认同)
  • 我的猜测是他想要最小化到托盘,但你得到我的+1来说小心. (3认同)
  • @Philip:嗯,这取决于.每次相关时(有更改)都应显示"是否要保存"框,取消应取消关机.例如,VS就是这样.应该显示一个恼人的"你想要关闭"...理想情况下,从来没有,但如果你这样做,你应该在关机时绕过. (2认同)

Phi*_*ace 19

重写OnFormClosing方法.

注意: 您需要检查CloseReason并仅在UserClosing时更改行为.你不应该在这里放任何会阻碍Windows关闭程序的东西.

应用程序关闭Windows Vista中的更改

这是来自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属性以确保执行适当的操作.如果用户尝试关闭表单,您可能只想执行备用操作.


Lor*_*uer 7

正如Jon B所说,但你也想检查ApplicationExitCallTaskManagerClosingCloseReason:

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)