在 UserClosing 和 this.close 上触发关闭事件

2024-05-12

我有一个表单,上面有一个 LogOutEvent 和一个表单关闭事件。 这是代码,

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;
            }
         }
}

我的问题是,当我单击“注销”按钮时,它会调用表单关闭事件。有人可以建议更好的代码吗?

当我单击关闭“X”时,它应该关闭应用程序,当我单击注销时,它应该关闭当前窗口并转到登录表单。


我确信有更好的解决方案,但这确实有效:

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
    }
}

这允许您的表单关闭事件处理程序识别另一个方法是否正在调用表单关闭,如果是,则跳过正常处理。

或者你也可以Hide而是使用表单,并在用户下次登录时重新使用相同的表单实例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 UserClosing 和 this.close 上触发关闭事件 的相关文章

随机推荐