VS2015 关闭 Windows 表单无法正常工作

VS2015 Closing Windows Form not working properly

我有VS2015 Windows Form,点击X关闭应用程序时,它会提示我是否关闭它。当我按否时,弹出窗口 window 将关闭。但是,当我按 Yes 时,它会弹出另一个相同的 window,并询问我是否关闭它。

我该如何解决这个问题?我想在第一个弹出窗口时关闭我的表单。

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            const string closemsg = "Do you really want to close the program?";
            const string exit = "Exit";

            DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo);

            if (dialog == DialogResult.Yes)
            {
                Application.Exit();
            }
            else if (dialog == DialogResult.No)
            {
                e.Cancel = true;
            }
        }

However, when I press Yes, it pops up another same window, and asks me to close it or not.

原因是因为你的Form1_FormClosing会被再次调用。尝试设置一个 _isExiting 标志,您可以在进入时进行测试。

试试这个:

bool _isExiting;

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (_isExiting) 
    {
        // whoops, been here already, time to go!
        return;
    }

    const string closemsg = "Do you really want to close the program?";
    const string exit = "Exit";

    DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo);

    if (dialog == DialogResult.Yes)
    {
        _isExiting=true; // set flag here so we don't repeat this exercise again
        Application.Exit();
    }
    else if (dialog == DialogResult.No)
    {
        e.Cancel = true;
    }
}  

很简单。 删除Application.Exit();

Application.Exit() 生成 FormClosing 事件。

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{ 
    const string closemsg = "Do you really want to close the program?";
    const string exit = "Exit";

    DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo);

    if (dialog == DialogResult.Yes)
    {
        //Remove Application.Exit();
        //Application.Exit();
    }
    else if (dialog == DialogResult.No)
    {
        e.Cancel = true;
    }
}