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)
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语句将被执行.
根据其他响应,您可以将其放入表单代码中:
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 方法还允许派生类在不附加委托的情况下处理事件。这是在派生类中处理事件的首选技术。