How to exit a Windows Forms application in C #

I am 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(); } 

for the class Form1 : Form , which is the form class that Visual Studio created automatically. But when this code works, I get the following message:

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

Additional Information: A general error occurred in GDI +.

Message Image:

Error message

What is the problem?

How do I exit the application?

+7
source share
3 answers

First you need to specify your line so that the message box knows what to do, and then you must exit the application, indicating the context of the application to exit.

 private void Defeat() { MessageBox.Show("Goodbye"); Application.Exit(); } 
+19
source

If you want to close the application, try the following:

  DialogResult dialog = new DialogResult(); dialog = MessageBox.Show("Do you want to close?", "Alert!", MessageBoxButtons.YesNo); if (dialog == DialogResult.Yes) { System.Environment.Exit(1); } 
0
source
 private void btnExit_Click(object sender, EventArgs e) { this.Close(); //"this" refers to the form } 
-2
source

All Articles