简体   繁体   中英

How to cancel closing winform?

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM