UserClosing和this.close同时触发关闭事件

本文关键字:事件 this close UserClosing | 更新日期: 2023-09-27 17:48:57

我有一个表单,上面有一个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");
        }
}

和Form Closing Event

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'时,它应该关闭应用程序,当我点击LogOut时,它应该关闭当前窗口并转到登录表单。

UserClosing和this.close同时触发关闭事件

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

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,并在下次用户登录时重用相同的表单实例

嗯…是的!表格快结束了;为什么不能触发事件?

如果CloseReason是没有帮助,然后只是抛出一个bool字段的形式,你设置为真,当你点击注销;并在结束事件中检查该字段