Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel closing winform?

Tags:

c#

winforms

When closing form, FormClosed event occurs, and I want to put some work when FormClosed event occurs like:

this.FormClosed += (s, e) => {
    var result = MessageBox.Show("Exit Program?", "Exit?", MessageBoxButtons.YesNo, MessageBoxIcons.Question);
    if (result == DialogResult.No) {
        return;
    } else {
        // Do some work such as closing connection with sqlite3 DB
        Application.Exit();
    }
};

The problem is that no matter I choose yes or no in the messagebox, the program gets closed. I need to abort program exit if I choose no, so how do I do that?

like image 335
cylee Avatar asked Dec 04 '25 07:12

cylee


2 Answers

The FormClosing (as opposed to your FormClosed) event's FormClosingEventArgs contains a Cancel boolean that you can change to true. Note that this will occur even if you close the form programmatically.

this.FormClosing += (s, e) => {
    var result = MessageBox.Show("Exit Program?", "Exit?", MessageBoxButtons.YesNo, MessageBoxIcons.Question);
    if (result == DialogResult.No) {
        e.Cancel = true;
    } else {
        // Do some work such as closing connection with sqlite3 DB
        Application.Exit();
    }
};

To determine how the form was closed, it also includes a CloseReason. See docs here and here.

like image 67
DiplomacyNotWar Avatar answered Dec 06 '25 20:12

DiplomacyNotWar


You can't use the FormClosed event, you need to use the FormClosing event and set e.Cancel to true.

The reason for that is that the FormClosed event occurs after the form has been closed, while the FormClosing event occurs as the form is being closed.

The FormClosingEventArgs class contains a boolean property called Cancel that you can set to true to stop the form from being closed.

like image 42
Zohar Peled Avatar answered Dec 06 '25 21:12

Zohar Peled