5

I want that the form will not close by doing Alt + F4 but if Application.Exit() or this.Close is called from the same Form, it should be closed.

I tried CloseReason.UserClosing but still no help.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Rick2047
  • 1,565
  • 7
  • 24
  • 35

4 Answers4

20

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;
    }
    
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Regent
  • 5,502
  • 3
  • 33
  • 59
2

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.

mahesh
  • 1,370
  • 9
  • 36
  • 61
0

Capture Alt+F4 hotkey by setting Form's KeyPreview property to true and overriding OnProcessCmdKey method.

Axarydax
  • 16,353
  • 21
  • 92
  • 151
0

How did you use CloseReason?

See the sample code here: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx

You need to set the Cancel property of the passed FormClosingEventArgs object to stop the form closing.

Mesh
  • 6,262
  • 5
  • 34
  • 53
  • The problem with `FormClosing` event is that Alt+F4 and calling `this.Close()` won't be distinguishable -- they both will have `CloseReason.UserClosing`. – Regent Apr 15 '10 at 08:54
  • prior to calling this.Close() set a property that can be examined in FormClosing... – Mesh Apr 15 '10 at 08:59
  • this will work it you can actually control where to call form's `Close` method. What if it could be called by some third-party component at some moment?.. Also, `CloseReason.UserClosing` will be set when clicking form's close box. (It is desired behaviour?) – Regent Apr 15 '10 at 09:06