Is it possible to disable the "close" button of a form using C #?

How to disable the button to close the form, as in the image below? (the image below shows the MessageBox window)

enter image description here

MessageBox above was created by me! I want to disable the close button of a regular form.

+7
source share
5 answers

You are handling the Close event (not a closed event) of the form.

And then you use e.CloseReason to decide whether you want to block it (UserClose) or not (TaskManager Close).

In addition, there is a small example of Disabling the close button in forms on codeproject .

+9
source

Right-click on the appropriate window and select "Properties". In the "Properties" section, click "Events." Double-click the FormClosing event.

The following code will be created in Windows Form Designer:

 private void myWindow_FormClosing(object sender, FormClosingEventArgs e) { } 

Just update the code to look like this (add e.Cancel = true; ):

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

You are done!

Alternatively, if you want to disable the close, maximize and reduce buttons of the window:

You can right-click on the window in question and click on "Properties". In the Properties section, set the ControlBox property to false .

+12
source

If you work with the MDI child window and disable the close button during window creation, you are excluded (i.e. you want to disable it at a certain time during the life of the form), none of the solutions proposed earlier will work¹.

Instead, we should use the following code:

 [DllImport("user32")] public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); [DllImport("user32")] public static extern bool EnableMenuItem(IntPtr hMenu, uint itemId, uint uEnable); public static void DisableCloseButton(this Form form) { // The 1 parameter means to gray out. 0xF060 is SC_CLOSE. EnableMenuItem(GetSystemMenu(form.Handle, false), 0xF060, 1); } public static void EnableCloseButton(this Form form) { // The zero parameter means to enable. 0xF060 is SC_CLOSE. EnableMenuItem(GetSystemMenu(form.Handle, false), 0xF060, 0); } 

¹ You can set ControlBox = false if you do not need any buttons, but this is not what the question asks.

+7
source

You must override the CreateParams function obtained from System.Windows.Forms.Form

And change the style of the class

 myCp.ClassStyle = 0x200; 
+3
source
  Closing += (s, eventArgs) => { DialogResult = DialogResult.None; //means that dialog would continue running }; 
0
source

All Articles