这是有问题的代码:
private void FormAccounting_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.FormAccountingLocation = this.Location;
Properties.Settings.Default.Save();
if (IsEditing)
{
MessageBox.Show("Please save or cancel open transactions before closing the accounting window.", "Open Transactions", MessageBoxButtons.OK, MessageBoxIcon.Information);
e.Cancel = true;
}
}
我已将断点添加到 e.Cancel = true;
行以确保它正在执行。
单击“确定”后表单立即关闭。
这是调用 FormAccounting 的代码:
private void buttonAccounts_Click(object sender, EventArgs e)
{
FormAccounting NewFormAccounting = new FormAccounting();
NewFormAccounting.Show();
}
最佳答案
取消表单关闭事件可以防止:
- 用户关闭表单
- Application.Exit 退出应用程序
- 在窗体上调用 Form.Close 的代码
但它不能阻止:
- 用户关闭应用程序的主窗体
- 在表单上调用 Form.Dispose 的代码
- 在应用程序的主窗口上调用 Form.Close 的代码
后3种情况甚至没有触发非主窗体上的窗体关闭事件,所以窗体没有机会取消它就消失了。也许您的应用程序导致表单首先以前三种方式之一关闭,这会触发事件,然后以后三种方式(或类似方式)之一关闭,这不会触发事件并强制关闭表单.
编辑: 将此函数添加到您的表单代码中,它将允许您在调试器中查看窗口关闭时调用堆栈的样子,以便您了解实际导致它的原因:
protected override void DestroyHandle()
{
System.Diagnostics.Debugger.Break();
base.DestroyHandle();
}
关于在 Form_FormClosing 事件中设置 e.Cancel = true 后,c# WinForms 表单仍然关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7091906/