[英]Canceling closing of C# Form
我的程序有两种关闭方法,一种是右上角的“ X”,另一种是“退出”按钮。 现在,当满足特定条件时按下其中任一按钮时,会弹出一条消息,通知用户他们尚未保存。 如果他们DID保存,该消息将不会弹出,并且程序将正常关闭。 现在,当消息确实弹出时,用户将获得带有“是”和“否”按钮的MessageBox。 如果按“是”,则需要保存程序。 如果按下“否”,则程序需要取消在用户按下“ X”或“退出”按钮时启动的关闭事件。
做这个的最好方式是什么?
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
TryClose();
}
private void TryClose()
{
if (saved == false)
{
//You forgot to save
//Turn back to program and cancel closing event
}
}
FormClosingEventArgs
包含一个Cancel
属性。 只需设置e.Cancel = true;
以防止表单关闭。
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (!saved)
e.Cancel = true;
}
编辑以回应评论:
由于您的目标是允许使用相同的“保存方法”,因此我将其更改为在成功时返回bool
:
private bool SaveData()
{
// return true if data is saved...
}
然后您可以编写:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Cancel if we can't save
e.Cancel = !this.SaveData();
}
而且您的按钮处理程序等都可以根据需要调用SaveData()
。
这将满足您的需求:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = !TryClose();
}
private bool TryClose()
{
return DialogResult.Yes == MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
}
使用事件args的Cancel
属性 ,将其设置为true即可取消。
要取消关闭事件,只需在FormClosingEventArgs
实例FormClosingEventArgs
Cancel
属性设置为true
FormClosingEventArgs
if (!saved) {
// Message box
e.Cancel = true;
}
您可以从退出按钮调用关闭。 然后像其他人所说的那样处理Forms.FormClosing事件中的关闭。 这将处理退出按钮单击和“ X”中的表单关闭
覆盖OnFormClosing:
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (saved == true)
{
Environment.Exit(0);
}
else /* consider checking CloseReason: if (e.CloseReason != CloseReason.ApplicationExitCall) */
{
//You forgot to save
e.Cancel = true;
}
base.OnFormClosing(e);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = !TryClose();
}
private bool TryClose()
{
if (!saved)
{
if (usersaidyes)
{
// save stuff
return true;
}
else if (usersaidno)
{
// exit without saving
return false;
}
else
{
// user cancelled closing
return true;
}
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.