单击关闭按钮时隐藏表单而不是关闭

iTE*_*Egg 58 .net c# winforms

当用户单击X表单上的按钮时,如何隐藏它而不是关闭它?

我曾尝试this.hide()FormClosing,但它仍然关闭窗体.

Ale*_*lex 94

像这样:

private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing) 
    {
        e.Cancel = true;
        Hide();
    }
}
Run Code Online (Sandbox Code Playgroud)

(通过Tim Huffman)

  • **注意!**你应该检查`e.CloseReason`(看另一个答案).否则,当表单因系统关闭或其他事件而关闭时,表单将不会关闭. (5认同)

Liz*_*izB 53

我在之前的回答中评论过,但我想我会提供自己的答案.根据您的问题,此代码与最佳答案类似,但添加了另一个提及的功能:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing) 
    {
        e.Cancel = true;
        Hide();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果用户只是X在窗口中点击,则表单隐藏; 如果其他任何事情,如任务管理器,Application.Exit()或Windows关闭,表单已正确关闭,因为该return语句将被执行.

  • 你对e.CloseReason的使用救了我!好答案! (2认同)

Jor*_*oba 8

来自MSDN:

要取消对表单的关闭,请将传递给事件处理程序的Cancel属性设置FormClosingEventArgstrue.

所以取消然后隐藏.


Ora*_*ace 5

根据其他响应,您可以将其放入表单代码中:

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        base.OnFormClosing(e);
        if (e.CloseReason == CloseReason.UserClosing)
        {
            e.Cancel = true;
            Hide();
        }
    }
Run Code Online (Sandbox Code Playgroud)

根据MSDN,首选覆盖:

OnFormClosing 方法还允许派生类在不附加委托的情况下处理事件。这是在派生类中处理事件的首选技术。