2

As a sample below, I am using an If statement for my Application, where if you press Yes, the Application should close. I click Yes, and No, and the Application just continues regardless. Does anyone know why this might happen?

if (diff_ULNDOB.Any())
{
     DialogResult result1 = System.Windows.Forms.MessageBox.Show("Cannot proceed with Cross Year checks! Please see Workbook " + output + "." + " Do you wish to close the Application?", "Error",
     MessageBoxButtons.YesNo);

    if (result1 == DialogResult.Yes)
    {
       System.Windows.Forms.Application.Exit();           
    }

    Progress.Error = true;
    break;
}
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114

2 Answers2

4

Add Environment.Exit(0); when you want to close your application.

Aars93
  • 379
  • 4
  • 10
3

I would use Application.Exit() as this is a cleaner way of doing it than Environment.Exit(0).

The advantages of using Application.Exit() is that is will allow the form to execute any cleanup processes like Form.OnClose which can include closing database connections and file handlers.

Enivornment.Exit(0) is the same as just directly killing the process, so if you use it make sure all connections and files have been released properly.


Above was for Windows Forms applications. If it is a console application, the best way of exiting the application is returning the relevant exit code in the Main method.

Tom Dee
  • 2,516
  • 4
  • 17
  • 25
  • Assuming this is a WinForm application, you are correct, but it seems this is just a console app. – Neil Feb 20 '19 at 10:49
  • @Neil you may be correct actually, I think the `MessageBox` threw me a little bit there! – Tom Dee Feb 20 '19 at 10:50