How to prevent or block closing a WinForms window?
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);
}
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;
}
}
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
}