Prevent Users Closing Your Windows Form

Windows Forms

Sometimes you might require to stop a user from closing your Windows form – maybe because the form is processing something in the background and you don’t want the user to break that process, or maybe because the user does not have access rights to close your application. Either way this is very simple to implement and I will show you how.

The quick way around this problem would be to hide the form’s control box. The problem with this approach is that the user can still hit Alt+F4 on their keyboard and close your form. You could try to catch the key presses and look for Alt and F4 but I do not recommend this approach.

The cleanest approach to solve this problem would be to subscribe to the Form.FormClosing event and cancel the closing process from there. This might sound a little difficult but it really is not – let me explain.

Subscribing to the Form.FormClosing event

There are two ways you can subscribe to a Form event when using Microsoft Visual Studio – either programmatically or by using Visual Studio’s IDE.

Subscribing to events programmatically

First you must create an event handler method which is the method that will be executed when the Form.FormClosing event fires. Here is an example:

private void FormIsClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true;
}

In the above example I created a method which has a signature that matches the signature of the FormClosingEventHandler Delegate since we want to catch the Form.FormClosing event. If you don’t know what a delegate is, don’t worry, it’s not important for this example. I will be explaining delegates in a future article. If you want more information on the FormClosingEventHandler Delegate you can click here. Then within the method, I am calling e.Cancel = true;. This line of code will stop the form from closing.

We are not ready yet – we still need to attach an event handle to our event handler method. The code for this is below:

this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormIsClosing);

This line of code is letting our program know that our method FormIsClosing() will be the Form.FormClosing event handler method. This line of code is usually placed within the private void InitializeComponent() method which is created automatically by Visual Studio when you create a new C# Windows Forms Application project.

Subscribing to events by using the Visual Studio IDE

This way of subscribing to the Form.FormClosing event is much easier than the previous method. Switch to the Design view of your Form in Visual Studio and follow these steps:

  1. If the Properties window is not visible, in Design view, right-click on the form for which you want to create the event handler, and select Properties.
  2. On top of the Properties window, click the Events icon.
  3. Double-click the FormClosing event. Visual C# creates an empty event handler method and adds it to your code automatically.
FormClosingEvent

If your form’s name was Form1 (which is the default form name) you should find a new method called Form1_FormClosing in your code. Now add the code e.Cancel = true; to the empty Form1_FormClosing method and you’re done.

Further Enhancements

If you have implemented one of the above examples you have successfully prevented users from closing your form. The only problem is that if the user tried to close the form but it remained open he/she might think that the form has stopped responding and might try to close your application using the Windows Task Manager for example. You probably do not want this to happen so I suggest you ask the user whether he/she wants to shut down the form when you detect that it is being closed.

To do this is also very easy. You already have your event handler method Form1_FormClosing. All you need to do now is the following code:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    switch (e.CloseReason)
    {
        case CloseReason.UserClosing:
            if (MessageBox.Show("Are you sure you want to exit?",
                                "Exit?",
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question) == DialogResult.No)
            {
                e.Cancel = true;
            }
            break;
    }
}

This code makes use of a switch statement to decide what to do according to the CloseReason property. If the user is trying to close the form, then e.CloseReason will be equal to CloseReason.UserClosing. In this case we are displaying a message box to the user and asking for a confirmation to exit. If the user selects ‘No’ we are setting e.Cancel = true; and therefore the form is not closed. If the user selects ‘Yes’ on the message box, the form will close.

I hope this article has helped you understand the techniques used to prevent a user from closing your form. Please feel free to leave any comments and stay tuned to this blog for more articles.

Dave

4 comments… add one
  • Abhishek Tiwary Link Reply

    Form is not closed after using this above code.

    • Rupesh Jaiswal Link Reply

      use this Code….
      private void Form1_FormClosing(object sender, FormClosingEventArgs e)

      {

      DialogResult dlg = MessageBox.Show(“You want to close Form?”, “Warning”, MessageBoxButtons.YesNo);

      if (dlg == DialogResult.No)

      e.Cancel = true;

      else if (dlg == DialogResult.No)

      e.Cancel = false;

      }

  • Android Link Reply

    Use this….

    private void FrmCargaPieza_FormClosing(object sender, FormClosingEventArgs e)
    {
    if (e.CloseReason == CloseReason.UserClosing)
    {
    if (MessageBox.Show(“Are you sure you want to exit?”, “Confirmation”,
    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {Application.Exit();}
    else{e.Cancel = true;}
    }
    }

  • Eduardo Rodrigues Link Reply

    Thank u so much 😀

Leave a Comment