If you are working with an MDI child window and disabling the close button during creation of the window is ruled out (i.e. you want to disable it at certain times during the form's life) none of the previously proposed solutions will work¹.
Instead we must 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 want any buttons, but that is not what the question is asking.