当关闭按钮被禁用时关闭表格程序
问题描述:
我想在按下按钮时关闭应用程序,但我想禁用关闭按钮(X按钮右上角)。当关闭按钮被禁用时关闭表格程序
我禁用了关闭按钮,此代码:
protected override void OnFormClosing(FormClosingEventArgs e)
{
e.Cancel = true;
}
但现在当我尝试使用此代码它不会工作关闭程序。
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
有没有一种方法是单击按钮时关闭该程序?
答
在事件处理程序,检查CloseReason property of the FormClosingEventArgs:
这可以让你的行为不同,这取决于how the close was initiated,所以在应用程序退出(或Windows关机)的情况下,可以允许的形式关闭。
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (e.CloseReason != CloseReason.ApplicationExitCall
&& e.CloseReason != CloseReason.WindowsShutDown)
{
e.Cancel = true;
}
}
答
您将取消总是窗体的关闭,所以这就是为什么它不起作用。
试试这个:
bool blockClosing = true;
protected override void OnFormClosing(FormClosingEventArgs e)
{
e.Cancel = blockClosing;
}
private void button1_Click(object sender, EventArgs e)
{
blockClosing = false;
Application.Exit();
}
这样,当您按下按钮,它可以让THA PP被关闭。
答
FormClosingEventArgs
有Reason
成员,告诉你究竟是想要关闭的形式。只需允许ApplicationExitCall
而不取消它。
这是一个非常残酷的用户体验。不要禁用关闭按钮;让他们使用它,如果他们想关闭程序。 – Servy