事件问题
本文关键字:问题 事件 | 更新日期: 2023-09-27 18:34:04
我正在使用带有"确定"和"取消"按钮的表单。当用户单击"取消"按钮时,用户将收到一条消息,确认表单是否应关闭。单击"确定"=关闭,但是单击"取消"时,表单不应关闭,但这就是正在发生的事情,我知道,我已经测试了为表单添加一些事件代码,但仍在关闭。我该怎么做才能让它正常工作?
// Button - Cancel
private void btnCancel_Click(object sender, EventArgs e)
{
// Message box to confirm or not
if (MessageBox.Show("Do you really want to cancel and discard all data?",
"Think twice!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.Yes)
{
// Yes
//this.Close(); // Closes the contact form
m_closeForm = false;
}
else
{
m_closeForm = false;
// No
// Do nothing, the user can still use the form
}
}
private void ContactForm_Formclosing(object sender, FormClosingEventArgs e)
{
if (m_closeForm)
e.Cancel = false; // Stänger formuläret. Inget skall hända
else
e.Cancel = true; // Stänger inte formuläret
}
您可以通过在窗体关闭事件中添加带有对话框结果的消息框来尝试以下操作。我相信这是更好的方法:
private void btnCancel_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you really want to cancel and discard all data?", "Think twice!",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
this.Close();
}
// Form wont close if anything else is clicked
}
private void btnOk_Click(object sender, EventArgs e)
{
// PerformAction()
this.Close();
}
我认为这就是你要找的。
我想你会发现在窗体的 Designer.cs 文件中,你会有以下行:
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
删除此行,无论客户 MessageBox 的结果如何,您的窗体将不再自动关闭。
要取消关闭,您可以使用FormClosingEventArgs
属性,即e.Cancel
true
。
在窗体FormClosing
事件中使用此代码。
if (MessageBox.Show("Do you really want to cancel and discard all data?",
"Think twice!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.Yes)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}