[c#] Using Exit button to close a winform program

I have an exit button on a winform that I want to use to close the program. I have added the button name to the FormClosed property found in the events section of the winforms properties. I thought that's all I had to do but when I click the button it does not close. I looked at the code and while a handler is created, there is no code inside of it. I don't know if that is correct or not. Here is the code that was created in the Form.cs file:

private void btnExitProgram_Click(object sender, EventArgs e)
    {

    }

What else do I have to do?

This question is related to c# winforms

The answer is


The FormClosed Event is an Event that fires when the form closes. It is not used to actually close the form. You'll need to remove anything you've added there.

All you should have to do is add the following line to your button's event handler:

this.Close();

If you only want to Close the form than you can use this.Close(); else if you want the whole application to be closed use Application.Exit();


Put this little code in the event of the button:

this.Close();

Remove the method, I suspect you might also need to remove it from your Form.Designer.

Otherwise: Application.Exit();

Should work.

That's why the designer is bad for you. :)


You can also do like this:

private void button2_Click(object sender, EventArgs e)
{
    System.Windows.Forms.Application.ExitThread();
}

In Visual Studio 2015, added this to a menu for File -> Exit and in that handler put:

this.Close();

but the IDE said 'this' was not necessary. Used the IDE suggestion with just Close(); and it worked.


Try this:

private void btnExitProgram_Click(object sender, EventArgs e) {
    this.Close();
}

We can close every window using Application.Exit(); Using this method we can close hidden windows also.

private void btnExitProgram_Click(object sender, EventArgs e) { Application.Exit(); }


Used Following Code

System.Windows.Forms.Application.Exit( )