Error closing Forms

Asked

Viewed 196 times

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 he falls in the if, executes the excerpt Application.Exit(); and returns to the beginning of the method by opening the MessageBox again. If I click sim again, then yes he close the form. Has anyone ever seen this ?

2 answers

2


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

When using Application.Exit(); the method is triggered FormClosing and generates a loop.

In the above example this is avoided.

  • Jay, thank you so much for your attention.

  • This time it is closing the winform, but unfortunately the process is not finished when closing the application. What may be occurring ?

2

It makes perfect sense for this to happen since the Application.Exit() as demonstrated the documentation triggers the event that will run your frmAgent_FormClosing. When you arrive at this method you already know that the application is leaving, you don’t have to say that it is to leave. You don’t have to do anything else. This should solve.

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

I put in the Github for future reference.

If you have to do something else, you can do but if you just wanted to do the confirmation, do not need to say to close, the normal flow if you do not say that is to cancel is to close.

Before using something always read the manual.

  • I would like to know what is the mistake here to have a -1?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.