How to prevent or block closing a WinForms window?

How can I prevent window closing by showing a MessageBox? (Technology:WinForms with C#)

When the close event occurs I want the following code to be run:

private void addFile_FormClosing( object sender, FormClosingEventArgs e ) {
    var closeMsg = MessageBox.Show( "Do you really want to close?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question );

    if (closeMsg == DialogResult.Yes) {
        //close addFile form
    } else {
        //ignore closing event
    }
}

Solution 1:

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    var window = MessageBox.Show(
        "Close the window?", 
        "Are you sure?", 
        MessageBoxButtons.YesNo);

    e.Cancel = (window == DialogResult.No);
}

Solution 2:

Catch FormClosing event and set e.Cancel = true

private void AdminFrame_FormClosing(object sender, FormClosingEventArgs e)
{
    var res = MessageBox.Show(this, "You really want to quit?", "Exit",
            MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
    if (res != DialogResult.Yes)
    {
      e.Cancel = true;
      return;
    }
}

Solution 3:

A special twist might be to always prevent just the user closing the form:

private void Frm_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = (e.CloseReason == CloseReason.UserClosing); 
    // disable user closing the form, but no one else
}

Solution 4:

Within your OnFormClosing event you can show the dialog and if answer is false (to not show) then set the Cancel property of the EventArgs to true.

Solution 5:

For prevent or block the form closing in particular situation you can use this strategy:

private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{

    if (FLAG_CONDITION == true)
    {
        MessageBox.Show("To exit save the change!!");
        e.Cancel = true;
    }

}