如何:使用 Windows 窗体“上下文菜单”组件添加和删除菜单项

介绍如何在 Windows 窗体中添加和移除快捷菜单项。

Windows 窗体 ContextMenu 组件提供与所选对象相关的常用命令的菜单。 可以通过将 MenuItem 对象添加到 MenuItems 集合,将项添加到快捷菜单。

可以永久删除快捷菜单中的项;但是,在运行时,隐藏或禁用项可能更合适。

重要

尽管 MenuStripContextMenuStrip 替换和添加以前版本的 MainMenuContextMenu 控件的功能,但如果选择,MainMenuContextMenu 都将保留,以实现后向兼容性和将来使用。

从快捷菜单中删除项

  1. 使用 Remove 组件的 RemoveAt 集合的 MenuItemsContextMenu 方法删除特定菜单项。

    ' Removes the first item in the shortcut menu.
    ContextMenu1.MenuItems.RemoveAt(0)
    ' Removes a particular object from the shortcut menu.
    ContextMenu1.MenuItems.Remove(mnuItemNew)
    
    // Removes the first item in the shortcut menu.
    contextMenu1.MenuItems.RemoveAt(0);
    // Removes a particular object from the shortcut menu.
    contextMenu1.MenuItems.Remove(mnuItemNew);
    
    // Removes the first item in the shortcut menu.
    contextMenu1->MenuItems->RemoveAt(0);
    // Removes a particular object from the shortcut menu.
    contextMenu1->MenuItems->Remove(mnuItemNew);
    

    -或-

  2. 使用 Clear 组件的 MenuItems 集合的 ContextMenu 方法从菜单中删除所有项。

    ContextMenu1.MenuItems.Clear()
    
    contextMenu1.MenuItems.Clear();
    
    contextMenu1->MenuItems->Clear();
    

另请参阅