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.
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.
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;
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With