Reputation: 113
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
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
Reputation: 1119
when using a button click to open a new form use USING
using (Form1 frm = new Form())
{
frm.ShowDialog();
}
Upvotes: 1
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...
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
Reputation: 789
I have used:
Environment.Exit(0);
Application.Exit();
and it was working for me on a project of mine.
Upvotes: 3