Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Form from closing when DialogResult is No

I am using following code on closing event of my Windows forms application form:

private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
    DialogResult dr = MessageBox.Show("Are you sure you want to quit?", "Leaving App",MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (dr == DialogResult.No)
    {
        return;
    }
    else
    Application.Exit();
}

But the problem is, whenever user clicks Yes the application ends but when user clicks No, the application is still running but the form hides. How can I keep form visible when user clicks No?

Update

Another problem I am facing is that, when I click Yes, the MessageBox displays again and then I click Yes the application exits. Why its displaying for two times?

like image 309
Shiva Pareek Avatar asked Dec 01 '22 03:12

Shiva Pareek


1 Answers

You don't have to call Application.Exit() because if you do not cancel closing it program will exit itself. Below is corrected code that is working:

private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
    DialogResult dr = MessageBox.Show("Are you sure you want to quit?", "Leaving App",MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (dr == DialogResult.No)
    {
        e.Cancel = true;
    }
}
like image 174
gzaxx Avatar answered Dec 04 '22 01:12

gzaxx