Disable 'X' Close Button On Your Windows Form Application

Recently, someone on MSDN forums asked this question on how to disable the “X” a.k.a. close button in his windows form application so the user is forced to close the application from the cancel button on the form and not from the close button. He wanted this for his application which requires registration first before a user can start using his application.

I don’t know the answer so I bing arond a bit and find a solution posted by someone though I don’t have the name but it worked like a charm….!!

We need some interoperability to do this, therefore get the namespace System.Runtime.InteropServices Code:

private const int MF_BYPOSITION = 0x400;
private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
private static extern int GetMenuItemCount(IntPtr hWnd);

Below code goes to the load event of your form:

IntPtr hMenu = GetSystemMenu(this.Handle, false);
int menuItemCount = GetMenuItemCount(hMenu);
RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);

Time to press ‘F5’….and the close button is now disabled on the form.

Windows Forms application with close button disabled

Download: CloseButton.zip (43.08 kb)

comments powered by Disqus