Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a Windows Forms Application in C#

Tags:

c#

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?

like image 739
SIMEL Avatar asked Mar 26 '13 23:03

SIMEL


People also ask

How do I close a Windows Form application?

Exit() Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.


2 Answers

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();
}
like image 64
bizzehdee Avatar answered Oct 05 '22 22:10

bizzehdee


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);
    }
like image 27
Dhanasekaran Avatar answered Oct 05 '22 22:10

Dhanasekaran