I want the form not to close by doing Alt+ F4, but if Application.Exit()or is called from the same form this.Close, it should be closed.
Application.Exit()
this.Close
I tried CloseReason.UserClosingbut still didn't help.
CloseReason.UserClosing
If you need to filter out the Alt+ event F4(leaving the click on the close button this.Close()and Application.Exit()behaving as usual), I can suggest the following:
this.Close()
KeyPreview
true
Connect form FormClosingand KeyDownevents:
FormClosing
KeyDown
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (_altF4Pressed) { if (e.CloseReason == CloseReason.UserClosing) e.Cancel = true; _altF4Pressed = false; } } private bool _altF4Pressed; private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.Alt && e.KeyCode == Keys.F4) _altF4Pressed = true; }
, , SuppressKeyPress true Form_Keydown EventHandler, .
if (e.KeyCode == Keys.F4 && e.Alt) { e.SuppressKeyPress = true; }
, SuppressKeyPress false eventHandller .
Capture Alt + F4, Form KeyPreview true overriding OnProcessCmdKey.
CloseReason?
. : http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx
You need to set the Cancel property for the passed FormClosingEventArgs object to stop closing the form.