VS2015关闭Windows窗体无法正常工作

时间:2015-10-06 00:46:50

标签: c# visual-studio visual-studio-2015 windows-forms-designer

我有VS2015 Windows窗体,每当我点击X关闭应用程序时,它会提示我关闭它。当我按否时,弹出窗口将关闭。但是,当我按“是”时,它会弹出另一个窗口,并要求我关闭它。

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

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

2 个答案:

答案 0 :(得分:2)

很简单。 删除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;
    }
}

答案 1 :(得分:1)

  

然而,当我按下是时,它会弹出另一个窗口,并要求我关闭它。

原因是因为您的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;
    }
}