Programming Newbie
Programming Newbie

Reputation: 1227

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?

Upvotes: 18

Views: 179390

Answers (10)

Ghotekar Rahul
Ghotekar Rahul

Reputation: 342

Used Following Code

System.Windows.Forms.Application.Exit( ) 

Upvotes: 2

Renz Macawili
Renz Macawili

Reputation: 1

You can also do like this:

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

Upvotes: 0

E J Chathuranga
E J Chathuranga

Reputation: 925

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(); }

Upvotes: 2

Anayetullah
Anayetullah

Reputation: 1

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();

Upvotes: 0

Brad Rogers
Brad Rogers

Reputation: 89

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.

Upvotes: 0

Thomas Lindvall
Thomas Lindvall

Reputation: 599

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. :)

Upvotes: 14

Justin Niessner
Justin Niessner

Reputation: 245429

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();

Upvotes: 4

juergen d
juergen d

Reputation: 204766

Try this:

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

Upvotes: 1

Abbas
Abbas

Reputation: 14432

Put this little code in the event of the button:

this.Close();

Upvotes: 1

bschultz
bschultz

Reputation: 4254

this.Close();

Closes the form programmatically.

Upvotes: 42

Related Questions