在UserClosing和this.close上触发了关闭事件 [英] Closing event triggered on both UserClosing and this.close
问题描述
我有一个表单,上面有一个LogOutEvent和一个表单关闭事件.这是代码,
I have a form on which there is a LogOutEvent and a form closing event. Here is the code,
private void btnLogOut_Click(object sender, EventArgs e)
{
DialogResult yesNo = MessageBox.Show(this, "Are you sure you want to Log Off?", "Log Off", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
if (yesNo == DialogResult.Yes)
{
new LoginForm();
this.Close();
string tst2 = Logout(AgentId, AgentPwd, ExtensionId);
if (tst2 == "TCF000")
MessageBox.Show(" Logout Success");
else
MessageBox.Show("Logout Failed");
}
}
还有一个表单关闭事件
private void MainGUI_FormClosing(Object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult yesNo = MessageBox.Show(this, "Are you sure you want to Log Off?", "Log Off", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
if (yesNo == DialogResult.Yes)
{
Application.Exit();
}
else
{
e.Cancel = true;
}
}
}
我的问题是,当我单击注销"按钮时,它会调用表单关闭事件.有人可以为此建议更好的代码吗?
My Problem is when i click on the LogOut button its calling the form closing event. Can anybody advice a better code for this?
当我单击关闭'X'时,它应该关闭该应用程序,而当我单击注销时,它应该关闭当前窗口并转到登录表单.
When i click on close 'X' it should close the application and when i click on LogOut it should close the current window and go to the login form.
推荐答案
我确定有更好的解决方案,但这确实有效:
I'm sure that there is a better solution, but this does work:
private bool loggingOut;
private void Form1_DoubleClick(object sender, EventArgs e)
{
this.loggingOut = true;
this.Close();
// This is optional as we are closing the form anyway
this.loggingOut = false;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing && !loggingOut)
{
// Handle form closing here
}
}
这使您的表单关闭事件处理程序可以识别是否有另一种方法正在调用表单关闭,并跳过正常的处理.
This allows your form closing event handler to identify if another method is invoking the form close, and skip the normal handling if it is.
或者,您可以<隐藏>隐藏表单,然后在用户下次登录时重新使用相同的表单实例.
Alternatively you could just Hide
the form instead, and re-use the same form instance the next time the user logs in.
这篇关于在UserClosing和this.close上触发了关闭事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!