c# - 在 UserClosing 和 this.close 上触发的关闭事件

标签 c# .net 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");
        }
}

还有一个表单关闭事件

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

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

或者,您可以只隐藏 表单,并在用户下次登录时重新使用相同的表单实例。

关于c# - 在 UserClosing 和 this.close 上触发的关闭事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5577023/

相关文章:

c# - 从 C++ 非托管应用程序检索 C# .NET 镜像

c# - 为什么这种从 int 到 uint 的隐式转换有效?

.net - 包含更多信息的 TreeView 节点

c# - 如何使用 .NET 创建 7-Zip 存档?

c# - 如何在数字前添加货币符号?

c# - 释放在 WPF Application.OnStartUp() : Which thread owns it? 中创建的命名互斥体

c# - 如何使用类型调用 default(T)?

c# - 是否有任何在 Windows 窗体应用程序中以最少设置使用 CefGlue 或 CefSharp 的示例?

c# - 这是 Cast<T> 在 Controls 集合上的正常行为吗?

c# - 以特定的最大字符数打印一个数字(或字符串)