void TagManagedMenuItems(Menu menu, int tag) { MENUINFO info = new MENUINFO(); info.cbSize = Marshal.SizeOf(info); info.fMask = MIM.MIM_MENUDATA; info.dwMenuData = tag; foreach (MenuItem item in menu.MenuItems) { ShellNativeMethods.SetMenuInfo(item.Handle, ref info); } }
void RemoveShellMenuItems(Menu menu) { const int tag = 0xAB; List <int> remove = new List <int>(); int count = ShellNativeMethods.GetMenuItemCount(menu.Handle); MENUINFO menuInfo = new MENUINFO(); MENUITEMINFO itemInfo = new MENUITEMINFO(); menuInfo.cbSize = Marshal.SizeOf(menuInfo); menuInfo.fMask = MIM.MIM_MENUDATA; itemInfo.cbSize = (uint)Marshal.SizeOf(itemInfo); itemInfo.fMask = (uint)MIIM.MIIM_ID | (uint)MIIM.MIIM_SUBMENU; // First, tag the managed menu items with an arbitary // value (0xAB). TagManagedMenuItems(menu, tag); for (int n = 0; n < count; ++n) { ShellNativeMethods.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 { ShellNativeMethods.GetMenuInfo(itemInfo.hSubMenu, ref menuInfo); if (menuInfo.dwMenuData != tag) { remove.Add(n); } } } // Remove the unmanaged menu items. remove.Reverse(); foreach (int position in remove) { ShellNativeMethods.DeleteMenu(menu.Handle, position, MF.MF_BYPOSITION); } }
public static extern bool GetMenuInfo(IntPtr hmenu, ref MENUINFO lpcmi);