退房时双重确认

Sea*_*ean 7 c# confirm exit winforms

我试图这样做,以便提示用户确认退出我的程序在c#,但由于某种原因,如果他们说"是"他们想退出,确认框将再次弹出.我无法弄清楚为什么.

    if (MessageBox.Show("Are you sure you want to exit?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
    {
        e.Cancel = true;
    }
    else { Application.Exit(); }
Run Code Online (Sandbox Code Playgroud)

小智 9

用这个

 private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("Are you sure you want to close?", "Infomate", MessageBoxButtons.YesNo) == DialogResult.No)
        {
            e.Cancel = true;
        }        
    }
Run Code Online (Sandbox Code Playgroud)


Meh*_*dad 5

啊,您检查CloseReasonFormClosing活动吗?我认为您可能由于两个不同的原因而获得同一事件(尽管我并不完全希望这种情况会正常发生);检查您FormClosingEventArgs的参数。


Sea*_*ean 5

啊,我想出了如何解决它。我删除了 Application.Exit(); 事件中的 FormClosing 事件,并将其移动到 FormClosed 事件中。现在一切正常。