1

Possible Duplicate:
How to Disable Alt + F4 closing form?

Help me pls.

How to make a modal form, that closes only from program code. I want to prevent form closing when user presses Alt+F4 etc.

I'm using MS VS C# 2010.

Community
  • 1
  • 1
Artem
  • 11
  • 1
  • Judging from a user perspective, let me add this off-topic advice: If the user is *not* permitted to close the form, then at the very least make sure that your form does not have a `[X]` close icon, nor a *Close* or *Cancel* button or anything else that suggests that the form is closable. If any of these things is present, then your form *should* close when the user requests it. (Sorry if this sounds patronising -- perhaps you've already taken care of the usability aspect.) – stakx - no longer contributing Aug 05 '11 at 11:35

2 Answers2

2

You could try to override the formClosing event.

Just go into Visual Studio, select your program's main form, look under options (f4) in the events tab. Look up FormClosing and handle your new code.

e.Cancel = true;

^ put that in the new code block and you'll prevent your application form closing on alt+f4

Pieter888
  • 4,882
  • 13
  • 53
  • 74
  • i tryed to put return; statement. But's no effect – Artem Aug 05 '11 at 11:27
  • Updated my answer. Note that this is the quick and dirty way of doing this, you can always specifically override the alt+f4 combination on the form. – Pieter888 Aug 05 '11 at 11:28
  • No problem, just note that now you won't be able to close your application using just `application.exit();` If you wish to close the program, remove the event first, then close. I'll update the answer if you wish but I'd suggest looking here:http://stackoverflow.com/questions/14943/how-to-disable-alt-f4-closing-form – Pieter888 Aug 05 '11 at 11:39
1
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
   // put your validation here.
   if (validations)
   {
      // Display a MsgBox asking the user to continue  or abort.
      if(MessageBox.Show("message...?", "My Application",
         MessageBoxButtons.YesNo) ==  DialogResult.Yes)
      {
         // Cancel the Closing event from closing the form.
         e.Cancel = true;
      }
   }
}
Damith
  • 62,401
  • 13
  • 102
  • 153