Form disable context menu items

How do I disable specific items (i.e. Close) in the context menu of the Windows form? Or if that's tricky to do, how do I disable the context menu?

Who is Participating?
Jaime OlivaresConnect With a Mentor Software ArchitectCommented:
Yes, it is pretty tricky. You will need some Interop. First define a helper class:

   public class WinApi
        public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
        public static extern bool RemoveMenu(IntPtr hMenu, UInt32 uPosition, UInt32 uFlags);

        public const Int32 WM_SYSCOMMAND = 0x0112;
        public const Int32 MF_SEPARATOR = 0x0800;
        public const Int32 MF_BYPOSITION = 0x0400;
        public const Int32 MF_BYCOMMAND = 0x0000;
        public const Int32 MF_POPUP = 0x0010;

        public const Int32 SC_CLOSE = 0xF060;
        public const Int32 SC_MOVE = 0xF010;
        public const Int32 SC_MINIMIZE = 0xF020;

then, inside your form's constructor:

            // Remove most system menu items
            IntPtr hMenu = WinApi.GetSystemMenu(this.Handle, false);
            if (hMenu != IntPtr.Zero)
                    WinApi.RemoveMenu(hMenu, WinApi.SC_CLOSE, WinApi.MF_BYCOMMAND);

you can remove other menu options as define in WinApi class
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.