- Context Menu Class
- Definition
- Examples
- Remarks
- Constructors
- Fields
- Properties
- Methods
- Events
- Практическое руководство. Добавление и удаление элементов меню с помощью компонента ContextMenu в Windows Forms How to: Add and Remove Menu Items with the Windows Forms ContextMenu Component
- Удаление элементов из контекстного меню To remove items from a shortcut menu
- Context Menu Конструкторы
- Определение
- Перегрузки
- ContextMenu()
- Комментарии
- См. также раздел
- Применяется к
- ContextMenu(MenuItem[])
- Параметры
- Примеры
- Notify Icon. Context Menu Свойство
- Определение
- Значение свойства
- Примеры
- Комментарии
- Control. Context Menu Свойство
- Определение
- Значение свойства
- Примеры
- Комментарии
- Примечания для тех, кто наследует этот метод
Context Menu Class
Definition
Represents a shortcut menu.
This class is not available in .NET Core 3.1 and later versions. Use ContextMenuStrip instead, which replaces and extends the ContextMenu control.
Examples
The following code example creates an event handler for the Popup event of the ContextMenu. The code in the event handler determines which of two controls a PictureBox named pictureBox1 and a TextBox named textBox1 is the control displaying the shortcut menu. Depending on which control caused the ContextMenu to display its shortcut menu, the control adds the appropriate MenuItem objects to the ContextMenu. This example requires that you have an instance of the ContextMenu class, named contextMenu1 , defined within the form. This example also requires that you have a TextBox and PictureBox added to a form and that the ContextMenu property of these controls is set to contextMenu1 .
Remarks
This class is not available in .NET Core 3.1 and later versions. Use instead.
The ContextMenu class represents shortcut menus that can be displayed when the user clicks the right mouse button over a control or area of the form. Shortcut menus are typically used to combine different menu items from a MainMenu of a form that are useful for the user given the context of the application. For example, you can use a shortcut menu assigned to a TextBox control to provide menu items for changing the font of the text, finding text within the control, or Clipboard features for copying and pasting text. You can also display new MenuItem objects in a shortcut menu that are not located within a MainMenu to provide situation specific commands that are not appropriate for the MainMenu to display.
Typically, a shortcut menu is displayed when a user clicks the right mouse button over a control or the form itself. Visible controls and Form have a ContextMenu property that binds the ContextMenu class to the control that displays the shortcut menu. More than one control can use a ContextMenu. You can use the SourceControl property to determine which control last displayed the shortcut menu in order to perform tasks specific to the control or to modify the shortcut menu displayed for the control.
You might want to know when the shortcut menu is being displayed in order to set check marks, disable items, and perform other menu tasks before the menu is displayed to the user. You can handle the Popup event to determine when the shortcut menu is being displayed.
In order to reuse MenuItem objects that are displayed in a MainMenu for use in a ContextMenu, you must create a copy of the menu using the CloneMenu method of the MenuItem class. You can also merge menu items and their submenu items into a single MenuItem object using the MergeMenu method of the MenuItem class.
Constructors
Initializes a new instance of the ContextMenu class with no menu items specified.
Initializes a new instance of the ContextMenu class with a specified set of MenuItem objects.
Fields
Specifies that the FindMenuItem(Int32, IntPtr) method should search for a handle.
(Inherited from Menu)
Specifies that the FindMenuItem(Int32, IntPtr) method should search for a shortcut.
(Inherited from Menu)
Properties
Gets a value indicating whether the component can raise an event.
(Inherited from Component)
Gets the IContainer that contains the Component.
(Inherited from Component)
Gets a value that indicates whether the Component is currently in design mode.
(Inherited from Component)
Gets the list of event handlers that are attached to this Component.
(Inherited from Component)
Gets a value representing the window handle for the menu.
(Inherited from Menu)
Gets a value indicating whether this menu contains any menu items. This property is read-only.
(Inherited from Menu)
Gets a value indicating the MenuItem that is used to display a list of multiple document interface (MDI) child forms.
(Inherited from Menu)
Gets a value indicating the collection of MenuItem objects associated with the menu.
(Inherited from Menu)
Gets or sets the name of the Menu.
(Inherited from Menu)
Gets or sets a value indicating whether text displayed by the control is displayed from right to left.
Gets or sets the ISite of the Component.
(Inherited from Component)
Gets the control that is displaying the shortcut menu.
Gets or sets user-defined data associated with the control.
(Inherited from Menu)
Methods
Copies the Menu that is passed as a parameter to the current Menu.
(Inherited from Menu)
Creates a new handle to the Menu.
(Inherited from Menu)
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Inherited from MarshalByRefObject)
Releases all resources used by the Component.
(Inherited from Component)
Disposes of the resources, other than memory, used by the Menu.
(Inherited from Menu)
Determines whether the specified object is equal to the current object.
(Inherited from Object)
Gets the MenuItem that contains the value specified.
(Inherited from Menu)
Returns the position at which a menu item should be inserted into the menu.
(Inherited from Menu)
Gets the ContextMenu that contains this menu.
(Inherited from Menu)
Serves as the default hash function.
(Inherited from Object)
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Gets the MainMenu that contains this menu.
(Inherited from Menu)
Returns an object that represents a service provided by the Component or by its Container.
(Inherited from Component)
Gets the Type of the current instance.
(Inherited from Object)
Obtains a lifetime service object to control the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Creates a shallow copy of the current Object.
(Inherited from Object)
Creates a shallow copy of the current MarshalByRefObject object.
(Inherited from MarshalByRefObject)
Merges the MenuItem objects of one menu with the current menu.
(Inherited from Menu)
Raises the Collapse event.
Raises the Popup event.
Processes a command key.
(Inherited from Menu)
Processes a command key.
Displays the shortcut menu at the specified position.
Displays the shortcut menu at the specified position and with the specified alignment.
Returns a String that represents the Menu control.
(Inherited from Menu)
Events
Occurs when the shortcut menu collapses.
Occurs when the component is disposed by a call to the Dispose() method.
(Inherited from Component)
Occurs before the shortcut menu is displayed.
Практическое руководство. Добавление и удаление элементов меню с помощью компонента ContextMenu в Windows Forms How to: Add and Remove Menu Items with the Windows Forms ContextMenu Component
Объясняется, как добавлять и удалять элементы контекстного меню в Windows Forms. Explains how to add and remove shortcut menu items in Windows Forms.
Компонент Windows Forms ContextMenu предоставляет меню часто используемых команд, относящихся к выбранному объекту. The Windows Forms ContextMenu component provides a menu of frequently used commands that are relevant to the selected object. В контекстное меню можно добавлять элементы, добавляя MenuItem объекты в MenuItems коллекцию. You can add items to the shortcut menu by adding MenuItem objects to the MenuItems collection.
Элементы контекстного меню можно удалить без возможности восстановления. Тем не менее во время выполнения может быть более уместно скрывать или отключать элементы. You can remove items from a shortcut menu permanently; however, at run time it may be more appropriate to hide or disable the items instead.
Хотя MenuStrip и ContextMenuStrip заменяют и добавляют функции к MainMenu ContextMenu элементам управления и предыдущих версий и MainMenu ContextMenu сохраняются для обратной совместимости и использования в будущем при выборе. Although MenuStrip and ContextMenuStrip replace and add functionality to the MainMenu and ContextMenu controls of previous versions, MainMenu and ContextMenu are retained for both backward compatibility and future use if you choose.
Удаление элементов из контекстного меню To remove items from a shortcut menu
Используйте Remove RemoveAt метод MenuItems коллекции ContextMenu компонента или для удаления определенного элемента меню. Use the Remove or RemoveAt method of the MenuItems collection of the ContextMenu component to remove a particular menu item.
Используйте Clear метод MenuItems коллекции ContextMenu компонента, чтобы удалить все элементы из меню. Use the Clear method of the MenuItems collection of the ContextMenu component to remove all items from the menu.
Context Menu Конструкторы
Определение
Инициализирует новый экземпляр класса ContextMenu. Initializes a new instance of the ContextMenu class.
Перегрузки
Инициализирует новый экземпляр класса ContextMenu без указания команд меню. Initializes a new instance of the ContextMenu class with no menu items specified.
Инициализирует новый экземпляр класса ContextMenu с указанным набором объектов MenuItem. Initializes a new instance of the ContextMenu class with a specified set of MenuItem objects.
ContextMenu()
Инициализирует новый экземпляр класса ContextMenu без указания команд меню. Initializes a new instance of the ContextMenu class with no menu items specified.
Комментарии
После использования этой версии конструктора можно добавить пункты меню в, ContextMenu используя Add метод Menu.MenuItemCollection класса. Once you have used this version of the constructor, you can add menu items to the ContextMenu by using the Add method of the Menu.MenuItemCollection class. Доступ к можно получить с Menu.MenuItemCollection помощью MenuItems Свойства. You can access the Menu.MenuItemCollection through the MenuItems property.
См. также раздел
Применяется к
ContextMenu(MenuItem[])
Инициализирует новый экземпляр класса ContextMenu с указанным набором объектов MenuItem. Initializes a new instance of the ContextMenu class with a specified set of MenuItem objects.
Параметры
Массив объектов MenuItem, представляющих добавляемые в контекстное меню команды. An array of MenuItem objects that represent the menu items to add to the shortcut menu.
Примеры
В следующем примере кода демонстрируется создание контекстного меню и использование Show метода. The following code example demonstrates constructing a shortcut menu and using the Show method. Чтобы выполнить пример, вставьте следующий код в форму, содержащую кнопку с именем Button1. To run the example, paste the following code in a form containing a button named Button1. Убедитесь, что все события связаны с их методами обработки событий. Ensure all events are associated with their event-handling methods.
Notify Icon. Context Menu Свойство
Определение
Возвращает или задает контекстное меню для значка. Gets or sets the shortcut menu for the icon.
Значение свойства
ContextMenu для значка. The ContextMenu for the icon. Значение по умолчанию — null . The default value is null .
Примеры
В следующем примере кода показано использование NotifyIcon класса для вывода значка для приложения в области уведомлений. The following code example demonstrates using the NotifyIcon class to display an icon for an application in the notification area. В примере показано задание Icon свойств, ContextMenu , Text и Visible и обработка DoubleClick события. The example demonstrates setting the Icon, ContextMenu, Text, and Visible properties and handling the DoubleClick event. Элемент ContextMenu с выходом на него присваивается NotifyIcon.ContextMenu свойству, которое позволяет пользователю закрыть приложение. A ContextMenu with an Exit item on it is assigned to the NotifyIcon.ContextMenu property, which allows the user to close the application. Когда DoubleClick происходит событие, форма приложения активируется путем вызова Form.Activate метода. When the DoubleClick event occurs, the application form is activated by calling the Form.Activate method.
Комментарии
Меню отображается, когда пользователь щелкает правой кнопкой мыши значок в области уведомлений панели задач. The menu is shown when the user right-clicks an icon in the notification area of the taskbar. Контекстные меню также называются всплывающими меню. Shortcut menus also are known as pop-up menus.
Control. Context Menu Свойство
Определение
Возвращает или задает контекстное меню, связанное с элементом управления. Gets or sets the shortcut menu associated with the control.
Значение свойства
Объект ContextMenu предоставляет контекстное меню, сопоставленное с элементом управления. A ContextMenu that represents the shortcut menu associated with the control.
Примеры
В следующем примере кода отображается значение, ContextMenu назначенное, TreeView при нажатии и отпускании правой кнопки мыши. The following code example displays the ContextMenu assigned to a TreeView when the right mouse button is clicked and released. Для этого кода требуется, чтобы у вас был объект Form с TreeView . This code requires that you have a Form with a TreeView on it. Также требуется, TreeView чтобы объект был ContextMenu назначен ContextMenu свойству. It is also required that the TreeView has a ContextMenu assigned to its ContextMenu property.
Комментарии
Используйте контекстные меню, чтобы предоставить пользователям параметры контекстного меню, если они щелкнули правой кнопкой мыши элемент управления. Use a shortcut menus to give context-specific menu options to users when they right-click on the control.
Примечания для тех, кто наследует этот метод
При переопределении ContextMenu свойства в производном классе используйте свойство базового класса ContextMenu для расширения базовой реализации. When overriding the ContextMenu property in a derived class, use the base class’s ContextMenu property to extend the base implementation. В противном случае необходимо предоставить всю реализацию. Otherwise, you must provide all the implementation. Переопределение get методов доступа и для свойства не требуется set ContextMenu ; при необходимости можно переопределить только одно из них. You are not required to override both the get and set accessors of the ContextMenu property; you can override only one if needed.