25

I'm writing a Windows Forms Application in C# that uses only one form. When I want to exit and close the application, I add the code

private void Defeat()
{
    MessageBox.Show("Goodbye");
    this.Close();
}

to the class Form1 : Form, which is the form class that was automatically created by Visual Studio. But when this code runs, I get the following message:

An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll

Additional information: A generic error occurred in GDI+.

A picture of the message:

Error message

What is the problem?

How should I exit my application?

3 Answers 3

37

You first need to quote your string so the message box knows what to do, and then you should exit your application by telling the application context to exit.

private void Defeat()
{
    MessageBox.Show("Goodbye");
    Application.Exit();
}
18

If you want to close the application, please try this:

    DialogResult dialog = new DialogResult();

    dialog = MessageBox.Show("Do you want to close?", "Alert!", MessageBoxButtons.YesNo);

    if (dialog == DialogResult.Yes)
    {
        System.Environment.Exit(1);
    }
1
  • This is the only one which is working for me on windows server 2019.
    – Mchurch
    Commented Oct 14, 2020 at 10:48
-2
private void btnExit_Click(object sender, EventArgs e)
{
  this.Close();  //”this” refers to the form
}
1
  • If you do this in a WinForms app, you'll end up with the exception 'System.ObjectDisposedException: 'Cannot access a disposed object.' in your program.cs->Main() method.
    – pwrgreg007
    Commented Jan 12, 2023 at 19:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.