Error when closing Forms

1

I have the following code snippet to close my application.

private void frmAgent_FormClosing(object sender, FormClosingEventArgs e)
{       

    if (MessageBox.Show("Deseja realmente fechar o sistema?", "Atenção!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) 
    {                
        Application.Exit();
    }
    else
    {
        e.Cancel = true;
    }

But when I click to close and click on sim it falls into if , it executes the Application.Exit(); excerpt and returns to the start of the method by opening MessageBox again. If I click on sim again, then it will close form . Has anyone seen this?

    
asked by anonymous 22.01.2015 / 16:20

2 answers

1

Change your code as the example below

        if (MessageBox.Show("Deseja realmente fechar o sistema?", "Atenção!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
        != DialogResult.Yes)
        {

            e.Cancel = true;
        }

Using Application.Exit(); fires the FormClosing method and generates a loop. In the example above this is avoided.

    
22.01.2015 / 16:45
2

It makes sense to do this since Application.Exit() as the documentation demonstrates triggers the event that will execute its frmAgent_FormClosing . When it arrives in this method already knows that the application is leaving, it does not have to say that it is to leave. You do not have to do anything else. This should resolve.

private void frmAgent_FormClosing(object sender, FormClosingEventArgs e) {       
    if (MessageBox.Show("Deseja realmente fechar o sistema?", "Atenção!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) {                
        e.Cancel = true;
    }

If you have to do something else, you can do but if you just wanted to make the confirmation, you do not have to say to close, the normal flow if you do not say it's to cancel is close.

Before using anything always read the manual.

    
22.01.2015 / 16:46