Context Menu Класс
Определение
Представляет контекстное меню. Represents a shortcut menu.
Этот класс недоступен в .NET Core 3,1 и более поздних версиях. This class is not available in .NET Core 3.1 and later versions. ContextMenuStripВместо этого следует использовать, который заменяет и расширяет ContextMenu элемент управления. Use ContextMenuStrip instead, which replaces and extends the ContextMenu control.
Примеры
В следующем примере кода создается обработчик событий для Popup события ContextMenu . The following code example creates an event handler for the Popup event of the ContextMenu. Код в обработчике событий определяет, какой из двух элементов управления PictureBox с именем pictureBox1 и TextBox именем textBox1 является элементом управления, отображающим контекстное меню. 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. В зависимости от того, какой элемент управления привел ContextMenu к отображению контекстного меню, элемент управления добавляет соответствующие MenuItem объекты в ContextMenu . Depending on which control caused the ContextMenu to display its shortcut menu, the control adds the appropriate MenuItem objects to the ContextMenu. В этом примере предполагается, что у вас есть экземпляр ContextMenu класса с именем contextMenu1 , определенный в форме. This example requires that you have an instance of the ContextMenu class, named contextMenu1 , defined within the form. В этом примере также требуется, чтобы в TextBox форму можно было PictureBox Добавить и, а ContextMenu свойству этих элементов управления присвоено значение contextMenu1 . 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 .
Комментарии
Этот класс недоступен в .NET Core 3,1 и более поздних версиях. This class is not available in .NET Core 3.1 and later versions. Взамен рекомендуется использовать . Use instead.
ContextMenuКласс представляет контекстные меню, которые могут отображаться, когда пользователь нажимает правую кнопку мыши над элементом управления или областью формы. 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. Контекстные меню обычно используются для объединения различных пунктов меню из MainMenu формы, которые полезны для пользователя при наличии контекста приложения. 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. Например, можно использовать контекстное меню, назначенное TextBox элементу управления, чтобы предоставить пункты меню для изменения шрифта текста, поиска текста в элементе управления или функций буфера обмена для копирования и вставления текста. 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. Можно также отобразить новые MenuItem объекты в контекстном меню, не расположенном в, MainMenu чтобы предоставить конкретные команды, которые не подходят для MainMenu вывода. 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. Видимые элементы управления и Form имеют ContextMenu свойство, которое привязывает ContextMenu класс к элементу управления, который отображает контекстное меню. Visible controls and Form have a ContextMenu property that binds the ContextMenu class to the control that displays the shortcut menu. Более одного элемента управления могут использовать ContextMenu . More than one control can use a ContextMenu. Можно использовать свойство, SourceControl чтобы определить, какой элемент управления последним отображал контекстное меню для выполнения задач, связанных с элементом управления, или для изменения контекстного меню, отображаемого для элемента управления. 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. Можно Popup выполнить обработку события, чтобы определить, когда отображается контекстное меню. You can handle the Popup event to determine when the shortcut menu is being displayed.
Чтобы повторно использовать MenuItem объекты, отображаемые в MainMenu , для использования в ContextMenu , необходимо создать копию меню с помощью CloneMenu метода MenuItem класса. 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. Можно также объединить пункты меню и их вложенные элементы в один MenuItem объект, используя MergeMenu метод MenuItem класса. You can also merge menu items and their submenu items into a single MenuItem object using the MergeMenu method of the MenuItem 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.
Указывает, что метод FindMenuItem(Int32, IntPtr) должен выполнять поиск дескриптора. Specifies that the FindMenuItem(Int32, IntPtr) method should search for a handle.
(Унаследовано от Menu)
Указывает, что метод FindMenuItem(Int32, IntPtr) должен выполнять поиск ярлыка. Specifies that the FindMenuItem(Int32, IntPtr) method should search for a shortcut.
(Унаследовано от Menu)
Свойства
Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.
(Унаследовано от Component)
Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.
(Унаследовано от Component)
Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.
(Унаследовано от Component)
Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.
(Унаследовано от Component)
Получает значение, представляющее дескриптор окна для меню. Gets a value representing the window handle for the menu.
(Унаследовано от Menu)
Получает значение, показывающее, содержит ли это меню какие-нибудь элементы меню. Gets a value indicating whether this menu contains any menu items. Это свойство доступно только для чтения. This property is read-only.
(Унаследовано от Menu)
Получает значение, указывающее объект MenuItem, используемый для отображения списка дочерних форм многодокументного интерфейса (MDI). Gets a value indicating the MenuItem that is used to display a list of multiple document interface (MDI) child forms.
(Унаследовано от Menu)
Получает значение, показывающее коллекцию объектов MenuItem, связанных с данным меню. Gets a value indicating the collection of MenuItem objects associated with the menu.
(Унаследовано от Menu)
Возвращает или задает имя таблицы для объекта Menu. Gets or sets the name of the Menu.
(Унаследовано от Menu)
Возвращает или задает значение, указывающее, размещается ли текст, отображаемый элементом управления, справа налево. Gets or sets a value indicating whether text displayed by the control is displayed from right to left.
Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.
(Унаследовано от Component)
Возвращает элемент управления, отображающий контекстное меню. Gets the control that is displaying the shortcut menu.
Получает или задает определяемые пользователем данные, связанные с элементом управления. Gets or sets user-defined data associated with the control.
(Унаследовано от Menu)
Методы
Копирует объект Menu, передаваемый в качестве параметра в текущий объект Menu. Copies the Menu that is passed as a parameter to the current Menu.
(Унаследовано от Menu)
Создает новый дескриптор для объекта Menu. Creates a new handle to the Menu.
(Унаследовано от Menu)
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Унаследовано от MarshalByRefObject)
Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.
(Унаследовано от Component)
Уничтожает ресурсы (кроме памяти), используемые классом Menu. Disposes of the resources, other than memory, used by the Menu.
(Унаследовано от Menu)
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Получает объект MenuItem, содержащий указываемое значение. Gets the MenuItem that contains the value specified.
(Унаследовано от Menu)
Возвращает позицию меню, в которую должен быть вставлен элемент меню. Returns the position at which a menu item should be inserted into the menu.
(Унаследовано от Menu)
Получает объект ContextMenu, содержащий это меню. Gets the ContextMenu that contains this menu.
(Унаследовано от Menu)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Получает объект MainMenu, содержащий это меню. Gets the MainMenu that contains this menu.
(Унаследовано от Menu)
Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.
(Унаследовано от Component)
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.
(Унаследовано от MarshalByRefObject)
Объединяет объекты MenuItem одного меню с текущим меню. Merges the MenuItem objects of one menu with the current menu.
(Унаследовано от Menu)
Вызывает событие Collapse. Raises the Collapse event.
Вызывает событие Popup. Raises the Popup event.
Обрабатывает клавишу для команд. Processes a command key.
(Унаследовано от 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.
Возвращает объект String, который представляет элемент управления Menu. Returns a String that represents the Menu control.
(Унаследовано от Menu)
События
Происходит при свертывании контекстного меню. Occurs when the shortcut menu collapses.
Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.
(Унаследовано от Component)
Происходит перед отображением контекстного меню. Occurs before the shortcut menu is displayed.