0

I want to close a application when a button is pressed but I wanted to disable the close button (X button upper right).

I disabled the close button with this code:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    e.Cancel = true;
}

But now when I try to close the program with this code it wont work.

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

Is there a way to close this program when the button is clicked?

stuartd
  • 70,509
  • 14
  • 132
  • 163
Gewoo
  • 437
  • 6
  • 19
  • 2
    This is a pretty cruel user experience. Don't disable the close button; let them use it if they want to close the program. – Servy Jan 06 '16 at 17:34

3 Answers3

2

In the event handler, check the CloseReason property of the FormClosingEventArgs:

This allows you to behave differently depending on how the close was initiated, so in the case of Application Exit (or Windows Shutdown) you can allow the form to close.

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (e.CloseReason != CloseReason.ApplicationExitCall
     && e.CloseReason != CloseReason.WindowsShutDown)
     {
          e.Cancel = true;
     }
}
stuartd
  • 70,509
  • 14
  • 132
  • 163
1

You're cancelling ALWAYS the closign of the form, so that's why it doesn't works.

Try this:

bool blockClosing = true;

protected override void OnFormClosing(FormClosingEventArgs e)
{
    e.Cancel = blockClosing;
}

private void button1_Click(object sender, EventArgs e)
{
    blockClosing = false;
    Application.Exit();
}

In this way, when you press your button it will allow tha pp to be closed.

Gusman
  • 14,905
  • 2
  • 34
  • 50
0

FormClosingEventArgs has a Reason member that tells you what exactly is trying to close your form. Simply allow ApplicationExitCall through without canceling it.

Blindy
  • 65,249
  • 10
  • 91
  • 131