Disable "X" Close Button On Your Windows Form Application

12. December 2010 07:55

C# Code Snippets  2 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
Code:

private 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);

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

Comments (2)

Dave Dave
1/7/2011 7:01:55 PM #

Why so difficult? Isn't it much easier to set Window.WindowStyle = WindowStyle.None (WPF) or Form.FormBorderStyle = FormBorderStyle.None (WinForms). There no need for P/invoke. Know you toolset!

Chris Chris
2/23/2015 7:41:33 AM #

Setting the WindowStyle to "None" also removes the title bar, but that's not what was asked for. (Disabling the X-Button != Removing the title bar).

Add Comment

Visit blogadda.com to discover Indian blogs Computers Blogs