Search code examples
c#.netwinformsmessageboxformclosing

How do prevent any Form from closing using alt + F4


This is not a duplicate of How to Disable Alt + F4 closing form?. Please read why.

I have made a custom MessageBox under my main Form.

enter image description here

And have set "Aight" button click listener as:

private void Aight_buton_Click(object sender, EventArgs e)
{
    dr = DialogResult.OK;
    Close();
}

The same is the case with the "X" button. Following the above question's answer I could have done this:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = e.CloseReason == CloseReason.UserClosing;
}

but since I am using Close() under the Aight_buton_Click it still registers as e.CloseReason == CloseReason.UserClosing;. So hitting the key doesn't close my form (a custom messagebox) nor does Alt+F4. I would like to know how specifically I can prevent only Alt+F4 closes and not the Close() closes. And please I would rather not use ModifierKeys as it is not the most appropriate not the smartest way to handle this situation.


Solution

  • Handle Atl+F4 by your self and set it handled.

    In the form constructor first set

    this.KeyPreview = true;
    

    Then handle the keyDown event

     private void Form1_KeyDown(object sender, KeyEventArgs e)
     {
         if (e.Alt && e.KeyCode == Keys.F4)
         {
             e.Handled = true;
         }
    
     }