【问题标题】:C# Application RestartC# 应用程序重启
【发布时间】:2016-03-31 05:04:41
【问题描述】:

我的 WinForms 应用程序上有一个使用此代码的注销选项:

    // restart the application once user click on Logout Menu Item
    private void eToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Restart();
    }

单击“注销”选项会弹出带有“是”或“否”的“您确定”框

private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
        //Double check if user wants to exit
        var result = MessageBox.Show("Are you sure you want to exit?", "Message",
        MessageBoxButtons.YesNo, MessageBoxIcon.Information);
        if (result == DialogResult.Yes)
        {
            e.Cancel = false;
        }
        else
        {
            e.Cancel = true;
        }
    }

,yes 没有问题,但是点击“No”仍然会重启应用程序,我该如何解决这个问题?

【问题讨论】:

  • 问题已更新@MickyD
  • 不要使用 ^^ 使用 @ 和此人的姓名,以便他们收到回复通知
  • 嗯,这没什么意义。请改用 Application.Exit()。
  • 嗯,我想知道Application.Restart()Application.Exit() 是否会杀死消息泵,使取消无关紧要?请尝试致电Close()。然后在您的 FormClosing 处理程序中,为 yes 调用 Application.Exit() 而对于 no 什么也不做
  • @MickyD Application.Exit() 效果很好。

标签: c# winforms logout


【解决方案1】:

把这样的对话框放在MenuItem_Click里面:

// restart the application once user click on Logout Menu Item
private void eToolStripMenuItem_Click(object sender, EventArgs e)
{
    //Double check if user wants to exit
    var result = MessageBox.Show("Are you sure you want to exit?", "Message",
    MessageBoxButtons.YesNo, MessageBoxIcon.Information);
    if (result == DialogResult.Yes)
    {
        Application.Restart();
    }
}

将 FormClosing 事件留空:

private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {


    }

另一种方法是,如果您绝对希望在 FormClosing 事件中实现对话框以覆盖 OnFormClosing()

你可以这样做:

 protected override void OnFormClosing(FormClosingEventArgs e) {

        //Double check if user wants to exit
        var result = MessageBox.Show("Are you sure you want to exit?", "Message",
        MessageBoxButtons.YesNo, MessageBoxIcon.Information);
        if (result == DialogResult.Yes)
            e.Cancel = true;
            base.OnFormClosing(e);
    }

在这种情况下,FormClosing 事件也将保持为空。

【讨论】:

    【解决方案2】:
      DialogResult confirm = MessageBox.Show("confirm Exit?", "exit", MessageBoxButtons.YesNo);
                if (confirm==DialogResult.Yes)
                    Application.Restart();
                else
                {
                    //do some thing
                }
    

    【讨论】:

    • 这只是在其自身上加倍,在关闭之前导致两个“确认退出”框。
    • 只需删除frmMain_FormClosing事件中的代码,仅在注销按钮上添加您的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多