Code to Disable close button on the form

abelLazm 2 Tallied Votes 549 Views Share

Add this code any where in your main form and You will be able to disable the X button on a winForm

private const int dis_close_button = 0x200;
 protected override CreateParams CreateParams
 {
     get
     {
        CreateParams ObjCP = base.CreateParams;
        ObjCP.ClassStyle = ObjCP.ClassStyle | dis_close_button ;
        return ObjCP;
     }
 }

Dani AI

Generated

’s technique changes the window class so the title‑bar close box isn’t created. That’s a simple, low‑level way to make the X disappear, but it’s worth understanding the tradeoffs and alternatives before using it.

The original approach only affects the button’s presence; it does not stop other ways the form can close (Alt+F4, calling Close() in code, system shutdown, Task Manager). To block user-initiated closes reliably handle the FormClosing event and cancel when appropriate:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // prevent user-initiated closes (click X, Alt+F4, system menu)
    if (e.CloseReason == CloseReason.UserClosing)
        e.Cancel = true;
}

If you want the X removed at runtime (instead of via the class style override), an alternative is to remove the SC_CLOSE command from the system menu. That uses a short P/Invoke sequence and updates the menu bar:

using System.Runtime.InteropServices;

const int SC_CLOSE = 0xF060;
const int MF_BYCOMMAND = 0x00000000;

[DllImport("user32.dll")] static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")] static extern bool RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
[DllImport("user32.dll")] static extern bool DrawMenuBar(IntPtr hWnd);

// call from Form.Load:
IntPtr hMenu = GetSystemMenu(this.Handle, false);
RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
DrawMenuBar(this.Handle);

Troubleshooting notes: class‑style changes take effect when the handle is created, so call RecreateHandle() if you change behavior after the form is shown. Restoring the system menu can be done by calling GetSystemMenu(this.Handle, true). Finally, removing or hiding standard window controls can confuse users — in most cases it’s better to keep the UI standard and prevent unwanted closes by validating in FormClosing (showing a confirmation or saving state) rather than permanently removing the X.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.