我正在为图书馆管理系统创建一个应用程序。
我想最初禁用关闭按钮,并在用户点击菜单后启用它 项目注销。
我有什么方法可以在我的应用程序中完成此功能吗?
我尝试在formClosing事件中使用以下代码,但它没有用完。
private void frmLibrary_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = false;
if (checkLogOff == false)
{
MessageBox.Show("Please Log Off before closing the Application");
e.Cancel = false;
this.ControlBox = false;
return;
}
else
{
this.ControlBox = true;
e.Cancel = true;
}
}
checkLogOff变量的值设置如下:
public bool checkLogOff = false;
private void logOffToolStripMenuItem_Click(object sender, EventArgs e)
{
checkLogOff = true;
/*Code to update the logoff users in the database*/
}
执行应用程序时,如果我没有单击LogOff菜单项,我将收到对话框,但在我按下消息框中的OK按钮后,应用程序关闭。但我不想让用户在单击LogOff MenuItem之前关闭应用程序。
请帮我完成这项任务。
提前致谢!
答案 0 :(得分:1)
我不会为此目的使用ControlBox
属性,因为它还会删除Maximize和Minimize按钮。您的代码的主要问题是您应该在Cancel
中将true
设置为FormClosing
以防止表单被关闭。我认为您的代码可以简化为此,并且仍然可以达到您想要的效果(假设我们不触及ControlBox
):
private void frmLibrary_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = !checkLogOff;
if (e.Cancel)
{
MessageBox.Show("Please Log Off before closing the Application");
}
}
答案 1 :(得分:1)
改变这个:
MessageBox.Show("Please Log Off before closing the Application");
e.Cancel = false;
this.ControlBox = false;
return;
对此:
MessageBox.Show("Please Log Off before closing the Application");
e.Cancel = true;
this.ControlBox = false;
return;
您没有取消表单加载。
答案 2 :(得分:0)
当checkLogOff == false时,您想取消该事件,因此您应将e.Cancel设置为True, 当checkLogOff == true时为False。
答案 3 :(得分:0)
你颠倒了e.Cancel的设置
必须是:
e.Cancel = true;
当您需要阻止应用程序关闭时。
==>
private void frmLibrary_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = false;
if (checkLogOff == false)
{
MessageBox.Show("Please Log Off before closing the Application");
e.Cancel = true; // <--
this.ControlBox = false;
return;
}
else
{
this.ControlBox = true;
e.Cancel = false; // <--
}
}
答案 4 :(得分:0)
我知道这不是你寻求的答案,而是告诉用户去另一个菜单项进行记录,如果他只是想要关闭应用程序,那就是Cubersome。
为什么告诉他需要注销?你不能代表他调用Logoff功能,或者显示一个询问他是否要注销的对话框?
答案 5 :(得分:0)
我强烈建议您针对e.CloseReason进行测试,并且只有在用户关闭操作时才执行取消逻辑,否则您的应用程序将阻止系统关闭,并且'结束此现在任务'对话框不会给用户留下好印象。