public static extern bool SetMenuInfo(IntPtr hmenu, ref MENUINFO lpcmi);
void RemoveShellMenuItems(Menu menu) { const int tag = 0xAB; List<int> remove = new List<int>(); int count = User32.GetMenuItemCount(menu.Handle); MENUINFO menuInfo = new MENUINFO(); MENUITEMINFO itemInfo = new MENUITEMINFO(); menuInfo.cbSize = (UInt32)Marshal.SizeOf(menuInfo); menuInfo.fMask = MIM.MIM_MENUDATA; itemInfo.cbSize = (UInt32)Marshal.SizeOf(itemInfo); itemInfo.fMask = MIIM.MIIM_ID | MIIM.MIIM_SUBMENU; // First, tag the managed menu items with an arbitary // value (0xAB). TagManagedMenuItems(menu, tag); for (int n = 0; n < count; ++n) { User32.GetMenuItemInfo(menu.Handle, n, true, ref itemInfo); if (itemInfo.hSubMenu == IntPtr.Zero) { // If the item has no submenu we can't get the tag, so // check its ID to determine if it was added by the shell. if (itemInfo.wID >= m_CmdFirst) remove.Add(n); } else { User32.GetMenuInfo(itemInfo.hSubMenu, ref menuInfo); if ((int)menuInfo.dwMenuData != tag) remove.Add(n); } } // Remove the unmanaged menu items. remove.Reverse(); foreach (int position in remove) { User32.DeleteMenu(menu.Handle, position, MF.MF_BYPOSITION); } }
void TagManagedMenuItems(Menu menu, int tag) { MENUINFO info = new MENUINFO(); info.cbSize = (UInt32)Marshal.SizeOf(info); info.fMask = MIM.MIM_MENUDATA; info.dwMenuData = (UIntPtr)tag; foreach (MenuItem item in menu.MenuItems) { User32.SetMenuInfo(item.Handle, ref info); } }