How do I disable the Close 'X' button in a Windows Form using C#


There is no direct way to disbale the X button (in property ) in a Windows Form, like there is a property for Maximize button called MaximizeBox = false Or Minimize Box = false.

I have used Win32 API to do so. It is implemented by importing unmanaged DLL [user32] and calling it's functions.

NotesBefore you use code, Please add a Close button in your form so that you can close your app.

Add the following library

using System.Runtime.InteropServices;

Declare the following as class level variable

const int MF_BYPOSITION = 0x400;

[DllImport("User32")]

private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);

[DllImport("User32")]

private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

[DllImport("User32")]

private static extern int GetMenuItemCount(IntPtr hWnd);

 

In the Form_Load() event, write the following code

private void Form1_Load(object sender, EventArgs e)

{

        IntPtr hMenu = GetSystemMenu(this.Handle, false);

        int menuItemCount = GetMenuItemCount(hMenu);

        RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);

}

 

Hope it will help you all. 

Cheers.

Up Next
    Ebook Download
    View all
    Learn
    View all