Question

In the Program.cs file of the .Net CF 3.5 WinForms program I've written, I launch the app by instantiating a new instance of Form1.

Application.Run(new Form1());

When I want to close/exit the application, I override the Form1 FormClosed event so that I can ensure exiting the application.

// In Form1 code-behind
private void OnFormClosed(object sender, EventArgs e)
{
    Application.Exit(); // Doesn't kill process
}

When this code runs, I want the app to disappear from the screen (close) and I want the process it was running as to die. The app closes (disappears), but unfortunately, the process (we'll call it app.exe) is still running indefinitely. When I start the app again and close it, it spins up another app.exe process, etc. So the process is never dying and more are being created eating memory.

How can I ensure this process is being killed when I close/exit the app? Thanks.

Was it helpful?

Solution

First, you should not have to overide OnFormClosed to get the behavior you're after. Just closing the Form passed in to Application.Run will cause the app's message pump to exit and should cause the process to end. For Windows Mobile you should set the ShowMinimize property of the Form to false to prevent it from just being minimized - you should have a (OK) in the upper right, not an (X).

If the process does not exit when this Form closes, then the culprit 99.99% of the time is that you have a worker thread that is still running preventing the process from closing. Make sure all of your Threads have IsBackground set to true (for CF 3.5) and as a precaution, all of your threads should also have some form of exit notification or flag. Don't rely of the process terminating to tear them down for you.

OTHER TIPS

Your problem is that you have Form.MinimizeBox = true. Change it to false and the form will be closed when ok is clicked instead of minimized when x is clicked.

There are more things to consider in your question:

I override the Form1 FormClosed event

  • There is no FormClosed event for forms of type System.Windows.Forms.Form, only Closing and Closed.
  • You don't override an event. You override a virtual function from a base class or interface.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top