Demo code on how to disable the X button in menu bar in a window. I found a lot of posts on this in VB, but none for C#. So if you are a C# fan like me, this is for you…
1. There is no direct way to disbale the X button, like there is a property for Maximize button called MaximizeBox = false.
2. This is implemented by importing unmanaged dll “user32” and calling it’s functions.
3. Before you use this code, make sure to add a Close button in your form so that you can close your app. See the attached screen shot Disabled.jpg. Below is the code for this form.
Add the following library
Declare the following as class level variable
constint 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);
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);
4. Run it. Voila! you are done. If you know of a ay to do it without calling unmanaged code, please do let me know.