我希望当用户关闭窗口时,会显示一个MessageBox并询问用户是否确定要关闭窗口。但是当我尝试时,窗口就会关闭,nevers会向我显示MessageBox。
private void SchetsWin_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
MessageBox.Show("Example");
}
}
答案 0 :(得分:8)
不要为表单本身连接事件,只需覆盖OnFormClosing方法即可。至于显示确认消息以确认它,只需检查MessageBox的DialogResult的值:
protected override void OnFormClosing(FormClosingEventArgs e) {
if (e.CloseReason == CloseReason.UserClosing) {
if (MessageBox.Show("Do you want to close?",
"Confirm",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.No) {
e.Cancel = true;
}
}
base.OnFormClosing(e);
}
要小心这样的功能 - 它有惹恼最终用户的倾向。
答案 1 :(得分:0)
protected override void OnFormClosing(FormClosingEventArgs e)
{ if (MessageBox.Show("Are you sure you want to Close?","Confirm",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.No) { e.Cancel = true; } }