Disable Alt+F4 but allow the form to be closed by code, CloseReason.UserClosing is not helping

If you need to filter out Alt + F4 event only (leaving clicking of close box, this.Close() and Application.Exit() to behave as usual) then I can suggest the following:

  1. Set form's KeyPreview property to true;
  2. Wire up form's FormClosing and KeyDown events:

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

It's very easy you can do it by set SuppressKeyPress property to true on Form_Keydown EventHandler as below.

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

        }

With this you can also close your active form by set SuppressKeyPress Property to false on same eventHandller or any other way.