我正在使用winforms + c#创建一个小项目,我有一个问题,我在项目中使用第二个表单作为对话框。当用户试图关闭它时,我想为他们提供一个确认屏幕,以防止在关闭表单时丢失任何数据。此对话框表格还将包含一个“家庭”主页。按钮,关闭对话框,再次将它们留在主窗口中。当在屏幕顶部按下窗口X按钮时,出现问题,要求我设置一个“关闭”表格。要管理的事件。然而,这会产生一个无限循环,我的当前代码如下所示。有什么方法可以避免这种情况吗?
private void frmCreateRoute_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult Safe_to_exit_check = MessageBox.Show("Are you sure you would like to go to the home screen? \n(Any entered data will be lost.)", "", MessageBoxButtons.YesNo);
if (Safe_to_exit_check == DialogResult.Yes)
{
this.Close();
}
}
和一个简单的:
private void Home_button_Click(object sender, EventArgs e)
{
this.Close();
}
用于主页按钮。
由于
答案 0 :(得分:4)
在FormClosing中,设置:
e.Cancel = true;
以防止关闭表单。不要在那里使用this.Close()
。
答案 1 :(得分:1)
如果用户选择与e.Cancel=true
不同的内容,则需要设置DialogResult.Yes
,否则请关闭表单:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
var result = MessageBox.Show("Are you sure you want to close the form?",
"Close", MessageBoxButtons.YesNoCancel);
if (result != System.Windows.Forms.DialogResult.Yes)
e.Cancel = true;
}