bengdahl
bengdahl

Reputation: 113

Windows form application not closing

I am making a Windows form app in c# and the process is never killed after I close the main form. The process sits in the background, taking up memory. I have tried many methods, such as Application.exit and Environment.exit, none of which have worked.

I have tried:

private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
    {
        Environment.Exit(0);
    }

And

static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
        Environment.Exit(0);
    }
}

I have tried both methods using both Application.Exit and Environment.Exit

I just want a solution that kills the process upon closing the main form

EDIT:

Upon closer inspection, this error only occurs when a button is pressed that switches to my project's second form using:

Form2 f = new Form2();
        f.Show();
        this.Hide();

Upvotes: 1

Views: 7561

Answers (3)

AndroidAL
AndroidAL

Reputation: 1119

when using a button click to open a new form use USING

 using (Form1 frm = new Form())
        {

            frm.ShowDialog();

        }

Upvotes: 1

Tom
Tom

Reputation: 2390

If it isn't already, you need to mark your main method with [STAThread] attribute (see https://stackoverflow.com/a/1361048/1497128), like so --

        [STAThread]
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

If it is, then make sure that...

  • ... all foreground threads are being terminated before the form closes
  • ... if you subscribe to FormClosing event then ensure you are not setting Cancel = true

Neither of your solutions are necessary, WinForm applications terminate the process when the main form is closed (assuming nothing else is blocking, such as another foreground thread). You can test this by creating a new WinForm project in Visual Studio, running it and closing the form.

Unless you are using specific logic to control when the application should exit, you definitely shouldn't need Environment.Exit(0) (mainly used for console apps) nor Application.Exit() (used with WinForm apps). Closing the form should do it, which can be done programmatically by calling form.Close().

Upvotes: 2

George Findulov
George Findulov

Reputation: 789

I have used:

Environment.Exit(0);
Application.Exit();

and it was working for me on a project of mine.

Upvotes: 3

Related Questions