void RemoveShellMenuItems(Menu menu) {
const int tag = 0xAB;
var remove = new List<int>();
int count = User32.GetMenuItemCount(menu.Handle);
var menuInfo = new MENUINFO();
var itemInfo = new MENUITEMINFO();
menuInfo.cbSize = Marshal.SizeOf(menuInfo);
menuInfo.fMask = MIM.MIM_MENUDATA;
itemInfo.cbSize = (uint)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 (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);
}
}