C# Programming > Windows Forms

C# Prevent Form Close

Windows Form Closing

The .NET Framework makes it very simple to prevent a Forms from closing. Which includes stopping Atl-F4 from closing the .NET application.

Preventing an application from closing is useful when programmers want to make sure the application does not exit in the middle of something important.

Closing Event

To stop the Form from closing we just need to make use of the FormClosing event. The event arguments object e has a property called Cancel. By setting Cancel to true, as you might guess, cancels the Form closing procedure.

So now that we stopped the Form from closing, how do we actually close the Form? Notice that commands such as this.Close() and Application.Exit will not work when executed inside the Form.

The solution is to keep a boolean field variable that will let us know when the application is "authorized" to close. This way when the programmer actually wants to close the Form, the field variable will flag the event to let the closing procedure through.


Of course this method uses Windows Forms events to prevent the application from exiting. .NET applications that do not use Forms will need a different method. Also this method does not prevent the user from killing the application process from the Task Manager.

Back to C# Article List