Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 957
Rishav Avatar asked Dec 24 '22 07:12

Rishav


2 Answers

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;
     }

 }
like image 70
Pavan Chandaka Avatar answered Jan 10 '23 06:01

Pavan Chandaka


Add a bool field to the form, set it to true in the Aight_buton_Click method, and in the Form1_FormClosing only prevent the form from being closed if that field is false.

So on the form level:

private bool _isAightButonClicked;

Set it to true in the Aight_buton_Click method:

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

Use it in the Form1_FormClosing method:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = e.CloseReason == CloseReason.UserClosing && !_isAightButonClicked;
}
like image 31
Zohar Peled Avatar answered Jan 10 '23 06:01

Zohar Peled