whoknows
whoknows

Reputation: 5

How to display a MessageBox in a FormClosing event to prompt for cancellation?

I am using this code but it does not work, what am I doing wrong?

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("This will close down the whole application. Confirm?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        MessageBox.Show("The application has been closed successfully.", "Application Closed!", MessageBoxButtons.OK);
    }
    else
    {
        e.Cancel = true;
        this.Activate();
    }
}

Upvotes: 0

Views: 3439

Answers (3)

Hans Passant
Hans Passant

Reputation: 941237

I'll guess that you copied this code from somewhere and forgot to actually subscribe the FormClosing event. Common trap in C#, VB.NET uses the Handles keyword to avoid mistakes like that. Select the form, click the lightning bolt icon in the Properties window and double-click FormClosing to add the code that subscribes the event.

That said, it doesn't actually make sense to write code like this. Events are for other code to get notifications, a class doesn't have to listen to its own events. In Winforms, every event is triggered by a protected OnXxxx() method that you can override. You can cut and paste the code below and fall in the pit of success, it doesn't require any extra code like the event subscription code to work. And best of all, it gives preference to custom event handlers first, the kind of code you don't know about (yet) and ought to get the first shot at dealing with the notification.

    protected override void OnFormClosing(FormClosingEventArgs e) {
        base.OnFormClosing(e);
        if (!e.Cancel) {
            if (MessageBox.Show("Really?", "Close", MessageBoxButtons.YesNo) != DialogResult.Yes) {
                e.Cancel = true;
            }
        }
    }

Upvotes: 4

Steve
Steve

Reputation: 216243

If this form has been opened with FormName.ShowDialog(), inside the FormClosing event it's not enough to set e.Cancel=True.
You need to set the FormName.DialogResult to DialogResult.None as clearly documented on MSDN

Upvotes: 0

Software Engineer
Software Engineer

Reputation: 3956

Does the event-handler attach to form ? To check, go to form Properties then to Events tab and see if Form1_FormClosing is present against FormClosing event.

Upvotes: 0

Related Questions