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

Cha*_*kay 5 .net c# winforms

我有一个表单,其中有一个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");
        }
}
Run Code Online (Sandbox Code Playgroud)

表格闭幕活动

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;
            }
         }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我点击LogOut按钮时,它调用表格结束事件.任何人都可以为此建议更好的代码吗?

当我点击关闭'X'时它应该关闭应用程序,当我点击LogOut时它应该关闭当前窗口并转到登录表单.

Jus*_*tin 5

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

这允许表单关闭事件处理程序识别另一个方法是否正在调用表单close,并跳过正常处理(如果是).

或者,您可以只Hide使用表单,并在用户下次登录时重复使用相同的表单实例.