1

On Application startup

public form1()
{
    InitializeComponent();
    dirPath1 = ConfigurationManager.AppSettings["path1"];
    dirPathath2 = ConfigurationManager.AppSettings["path2"];
    if ((!Directory.Exists(dirPath1)) && (!Directory.Exists(dirPath2)))
    {
        this.Close();              
        Application.Run(new form2());
    }

    //rest of code
}

On Form2 cancel button click

private void btnCancel_Click(object sender, EventArgs e)
{
    Application.Exit();            
}

According to me, application should be stopped now. But what it does, is continue executing the "rest of code" part in form1 constructor.

Gautam G
  • 494
  • 2
  • 6
  • 15
  • See http://stackoverflow.com/questions/8507978/exiting-a-c-sharp-winforms-application you have other threads running – Paul Zahra Sep 06 '13 at 08:00
  • 1
    of course that's how it works. `Application.Exit()` just exits the message loop (which is started right at the call `Application.Run`), all the code after `Application.Run` will be executed then. – King King Sep 06 '13 at 08:01

2 Answers2

1

Application.Exit() will exits the message loop only which is the loop after you call Application.Run .. If you want to exit from whole application-

try

  Environment.Exit(0)

It would just kill the process.

Microsoft DN
  • 9,706
  • 10
  • 51
  • 71
  • There is no overload of `Environment.Exit()` taking zero argument, so you should remove the first line (after `try`). – King King Sep 06 '13 at 08:12
0

You don't show the use of any threads in your code, but let's suppose you do have threads in it. To close all your threads you should set all of them to background threads before you start them, then they will be closed automatically when the application exits, e.g.:

Thread myThread = new Thread(...);
myThread.IsBackground = true; // <-- Set your thread to background
myThread.Start(...);

then try with

 Application.Exit(); 
Thilina H
  • 5,754
  • 6
  • 26
  • 56