Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi everyone,

Please how do I disable the ALT + F4 Key from closing my application.

Thanks
Posted

Handle Form.FormClosing[^] event and set e.Cancel = true. And perhaps check CloseReason[^] :-)
 
Share this answer
 
v2
Comments
Reiss 14-Jul-11 11:43am    
This will stop the form from closing in all cases and the CloseReason will only tell you UserClosing and not give any details about the whether it was invoked via the ALT-F4 key stroke combination.
Kim Togo 14-Jul-11 13:45pm    
And CloseReason.UserClosing says:
"The user is closing the form through the user interface (UI), for example by clicking the Close button on the form window, selecting Close from the window's control menu, or pressing ALT+F4."

Then it covers all "UserClosing" events.
If it is only the Alt+F4 you want to prevent. Then look at Solution 2
Sergey Alexandrovich Kryukov 14-Jul-11 15:02pm    
So, what's the problem? It's not "only", this is all what needed. On can assign Cancel=true on some conditions.
--SA
Sergey Alexandrovich Kryukov 14-Jul-11 15:00pm    
Absolutely, my 5.
And OP should not forget for conditions used to exit application when it is really needed. Among other things, Application.Exit can be used for unconditional exit.
--SA
Kim Togo 15-Jul-11 3:38am    
Thanks SA.
This is in C#, but should be easy enough to alter.

It is a bit of a hack to be honest

Declare a member var on the form
private bool ALT_F4 = false;


Handle the form closing event
C#
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
  if (ALT_F4)
  {
    e.Cancel = true;
    return;
  }
}


Handle the key down event on the form
C#
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
  ALT_F4 =(e.KeyCode.Equals(Keys.F4) && e.Alt == true) ;
}


For Code conversion

Convert C# to VB.NET[^]
 
Share this answer
 
v2
Comments
Philippe Mori 14-Jul-11 19:51pm    
Why check for Alt+F4. Any way of closing the form should be handled the same way...
Best Ways to get key is


if (e.KeyCode == (Keys)115)
{
//ALT + F4 pressed
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900