Disable Alt + F4, but allow code to close the form, CloseReason.UserClosing does not help

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.

I tried CloseReason.UserClosingbut still didn't help.

+5
source share
4 answers

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:

  • Set the form KeyPreview property true;
  • Connect form FormClosingand KeyDownevents:

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

, , SuppressKeyPress true Form_Keydown EventHandler, .

        if (e.KeyCode == Keys.F4 && e.Alt)
        {
            e.SuppressKeyPress = true;

        }

, SuppressKeyPress false eventHandller .

+3

Capture Alt + F4, Form KeyPreview true overriding OnProcessCmdKey.

0

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.

0
source

All Articles