1

I know this code can exit my application

System.Windows.Forms.Application.Exit();

But how to apply this code for all my form Let say I have a lot of form Do I have to put this code in every form?

Polamin Singhasuwich
  • 1,646
  • 2
  • 11
  • 20
  • When the main form exits, the application will end. – Poul Bak Apr 06 '16 at 09:11
  • 1
    It really depends on what you need. If you want to close application on any from close, then yes you need to subscribe to `Form_Closing` event on each Form and perform this logic. – Hari Prasad Apr 06 '16 at 09:11
  • What about if my main form is a login form so user have to logout first and then close my application? – Polamin Singhasuwich Apr 06 '16 at 09:14
  • @HariPrasad you're right, but `Exit` won't raise the `Form_Closing` event, so have to use `Close`instead of `Exit` – daniel59 Apr 06 '16 at 09:14
  • If you do not have a good hierarchy between windows then it gets to be pretty confusing to the user how to properly end your app. Do avoid hiding windows, that just makes it confusing to your code as well. Another approach is to simply keep it running as long as there is *any* window. [Like this](http://stackoverflow.com/a/10769349/17034). – Hans Passant Apr 06 '16 at 09:21

4 Answers4

0

Wrap this line inside a static method inside the class containing the Main()....that makes it somewhat modular, not much useful though.

SamGhatak
  • 1,487
  • 1
  • 16
  • 27
0

You can try to use

this.close();

to close your currently active form. Similarly you can use it every form you want to close.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Refered to my comment you can call the Close-method and use FormClosing-event to close the other forms:

public partial class Form1 : Form
{
    Form2 form2;
    public Form1()
    {
        InitializeComponent();
        FormClosing += Form1_FormClosing;
        form2 = new Form2();
        form2.Show();
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        form2.Close();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Close();
    }
}

In this example Form1 is your MainForm and if you close Form1 whether you use the Close-method or by closing the form by the default button the FormClosing event will be raised and all other forms will be closed too.

If you want to kill the current Process you can use this code:

Process.GetCurrentProcess().Kill();
daniel59
  • 906
  • 2
  • 14
  • 31
0

In many windows forms projects I've worked we had a base form and all forms in our code inherited from this base form, so you can have a form like below and you just change the others forms to inherit from this one.

public partial class frmBase: Form
{
    public frmBase()
    {
        InitializeComponent();
    }

    private void frmBase_FormClosed(object sender, FormClosedEventArgs e)
    {
        System.Windows.Forms.Application.Exit();
    }           
}
Henrique
  • 602
  • 4
  • 18