[英]prohibit user from closing the form
I have a main form called Form_Main
, when somebody wants to close it, it will close the entire application (by entire application I mean quitting other forms as well). 我有一个名为
Form_Main
的主窗体,当有人要关闭它时,它将关闭整个应用程序(通过整个应用程序我也要退出其他窗体)。 Therefore I prepared a yes/no MessageBox that ask users if they really want to quit the form. 因此,我准备了一个Yes / No MessageBox,询问用户是否真的要退出表单。 Here's where I'm at:
我在这里:
private void Form_Main_FormClosed(object sender, FormClosedEventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure?", "Confirmation", MessageBoxButtons.OKCancel);
if (result == DialogResult.OK)
{
Environment.Exit(1);
}
else
{
//does nothing
}
}
The "OK" button works. “确定”按钮起作用。 But when users clicks "Cancel",
Form_Main
is closed, but the application is still running (other forms are untouched). 但是,当用户单击“取消”时,
Form_Main
已关闭,但应用程序仍在运行(其他表单未Form_Main
)。 What should I replace //does nothing
with? 我应该用
//does nothing
代替//does nothing
?
Use the FormClosing
event (instead of FormClosed
), and then set e.Cancel = true
: 使用
FormClosing
事件(而不是FormClosed
),然后设置e.Cancel = true
:
private void Form_Main_FormClosing(object sender, FormClosingEventArgs e)
{
var result = MessageBox.Show("Are you sure?", "Confirmation", MessageBoxButtons.OKCancel);
e.Cancel = (result != DialogResult.OK);
}
The FormClosing
event occurs before the form actually closes, so you still have a chance to cancel it. FormClosing
事件在窗体实际关闭之前发生,因此您仍然有机会取消它。 By the time you get to the FormClosed
event, it's too late. 当您到达
FormClosed
事件时,为时已晚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.