I have a form app with two Forms. In the second form I have in the right corner the x
button. How I can make when I make click on this button to close the app, not just hide the Form2 window?
First you need to catch the event. To do that, set an event handler on the child form's FormClosing
event.
Then there are several options:
"Brute force" termination using Process.Kill()
.
This will terminate the process without letting any cleanup code to run. It has an effect like ending a process through the task manager. You can get the current process with Process.GetCurrentProcess
. Use like this:
Process.GetCurrentProcess().Kill();
"Gentle" termination by way of closing all windows using Application.Exit()
.
This will close all message pumps and windows, but will do so while allowing normal cleanup code to run. It does not however guarantee the process will be terminated, for example if a forgound thread is still active after message loops are done. Use like this:
Application.Exit();
Communicate intentions to the main thread.
This is a design solution, not a "line of code" you put somewhere. The idea is that the 2 classes (of the 2 forms) have some communication mechanism (via message, events or whatever you see fit and probably already use), and the child form notifies the parent form the user wants the exit the application. Then it's up to the main form to cleanup everything, close all forms (itself and others), and exit the process normally. This is the cleanest and preferred method, but requires a proper design and more code.