Share via


如何:使用 Windows 窗体 ContextMenu 组件添加和移除菜单项

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

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

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

重要

虽然 MenuStripContextMenuStrip 取代了以前版本的 MainMenuContextMenu 控件并向其中添加了功能,但也可选择保留 MainMenuContextMenu 以备后向兼容和供将来使用。

从快捷菜单中删除项

  1. 使用 ContextMenu 组件的 MenuItems 集合的 RemoveRemoveAt 方法删除特定菜单项。

    ' 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. 使用 ContextMenu 组件的 MenuItems 集合的 Clear 方法从菜单中删除所有项。

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

另请参阅