How to Disable Alt + F4 closing form?


What is the best way to disable Alt + F4 in a c# win form to prevent the user from closing the form?

I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.

2/11/2014 7:59:08 PM

Accepted Answer

This does the job:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    e.Cancel = true;

Edit: In response to pix0rs concern - yes you are correct that you will not be able to programatically close the app. However, you can simply remove the event handler for the form_closing event before closing the form:

this.FormClosing -= new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
9/2/2018 4:43:29 PM

If you look at the value of FormClosingEventArgs e.CloseReason, it will tell you why the form is being closed. You can then decide what to do, the possible values are:

Member name - Description

None - The cause of the closure was not defined or could not be determined.

WindowsShutDown - The operating system is closing all applications before shutting down.

MdiFormClosing - The parent form of this multiple document interface (MDI) form is closing.

UserClosing - 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.

TaskManagerClosing - The Microsoft Windows Task Manager is closing the application.

FormOwnerClosing - The owner form is closing.

ApplicationExitCall - The Exit method of the Application class was invoked.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow