Ilya Melamed Ilya Melamed - 2 months ago 6
C# Question

How to exit a Windows Forms Application in C#

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

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


Inside the class
Form1 : Form
, which is the form class that was automaticly created by Visual Studio. But when this code runs, I get the fallowing 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?

Answer

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

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