Disable "X" Close Button On Your Windows Form Application

12. December 2010 07:55

C# Code Snippets  Comments

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

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.

Download: CloseButton.zip (43.08 kb)

 No Rating