0

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?

Amit
  • 45,440
  • 9
  • 78
  • 110
uid
  • 247
  • 3
  • 11

2 Answers2

7

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:

  1. "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();
    
  2. "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();
    
  3. 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.

Amit
  • 45,440
  • 9
  • 78
  • 110
  • I used this private void Form2_FormClosed(object sender, FormClosedEventArgs e) { Process.GetCurrentProcess().Kill(); }, But don't works – uid Oct 13 '15 at 07:15
  • @user - Is the event handler being executed? (Use a debugger to validate) – Amit Oct 13 '15 at 07:22
  • when I make debug .. when I make click on X do not enter on this method – uid Oct 13 '15 at 07:24
  • Is the method attached to the event (`form2.FormClosed += Form2_FormClosed;` or something)? – Amit Oct 13 '15 at 07:28
  • no .. I need to put this after Initialize Component() ? – uid Oct 13 '15 at 07:30
  • It's best if you let the IDE handle this. Go to the design view, select your form, and double click the `FormClosed` event in the properties window. – Amit Oct 13 '15 at 07:31
0

If you are using form the simplest is using

this.Close(); or  Application.Exit();
bot
  • 4,841
  • 3
  • 42
  • 67