Windows form main menu

Form. Menu Свойство

Определение

Получает или задает меню MainMenu, которое отображается в форме. Gets or sets the MainMenu that is displayed in the form.

Значение свойства

Объект MainMenu, представляющий меню для отображения в форме. A MainMenu that represents the menu to display in the form.

Примеры

В следующем примере создается объект MainMenu , который присваивается двум MenuItem объектам MainMenu и привязывается к форме. The following example creates a MainMenu, assigns two MenuItem objects to the MainMenu and binds it to a form. В этом примере необходимо создать объект с Form именем Form1 . This example requires that you have a Form created that is named Form1 .

Комментарии

Это свойство можно использовать для переключения между полными наборами меню во время выполнения. You can use this property to switch between complete menu sets at run time. Например, можно определить, что он MainMenu будет отображаться, если в форме многодокументного интерфейса (MDI) нет активных дочерних форм MDI, а другой MainMenu для отображения при отображении дочернего окна. For example, you can define one MainMenu to be displayed when your multiple-document interface (MDI) form has no active MDI child forms and another MainMenu to display when a child window is displayed. Кроме того, можно использовать разные MainMenu условия, если в приложении есть определенные конкретные ситуации, требующие отображения другого набора меню. You can also use a different MainMenu when specific conditions exist in your application that require displaying a different menu set.

Main Menu Class

Definition

Represents the menu structure of a form.

This class is not available in .NET Core 3.1 and later versions. Use MenuStrip instead, which replaces and extends the MainMenu control.

Examples

The following code example creates a MainMenu, assigns two MenuItem objects to the MainMenu and binds it to a form. This example requires that you have a Form created that is named Form1 .

Remarks

This class is not available in .NET Core 3.1 and later versions. Use instead.

The MainMenu control represents the container for the menu structure of a form. A menu is composed of MenuItem objects that represent the individual menu commands in the menu structure. Each MenuItem can be a command for your application or a parent menu for other submenu items. To bind the MainMenu to the Form that will display it, assign the MainMenu to the Menu property of the Form.

For applications that will have support for multiple languages, you can use the RightToLeft property to display the text of the menu from right to left to support languages such as Arabic.

You can create different MainMenu objects to represent different menu structures for your form. If you want to reuse the menu structure contained in a specific MainMenu, you can use its CloneMenu method to create a copy. Once you have a copy of the menu structure, you can make the appropriate modifications for your new menu structure.

Cutting and pasting menu items from one form to another in the designer might not work as expected if the form you are pasting into has no menu items defined.

Constructors

Initializes a new instance of the MainMenu class without any specified menu items.

Initializes a new instance of the MainMenu class with the specified container.

Initializes a new instance of the MainMenu with a specified set of MenuItem objects.

Fields

Specifies that the FindMenuItem(Int32, IntPtr) method should search for a handle.

(Inherited from Menu) FindShortcut

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) Container

Gets the IContainer that contains the Component.

(Inherited from Component) DesignMode

Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component) Events

Gets the list of event handlers that are attached to this Component.

(Inherited from Component) Handle

Gets a value representing the window handle for the menu.

(Inherited from Menu) IsParent

Gets a value indicating whether this menu contains any menu items. This property is read-only.

(Inherited from Menu) MdiListItem

Gets a value indicating the MenuItem that is used to display a list of multiple document interface (MDI) child forms.

Читайте также:  Классическое меню пуск classic shell для windows

(Inherited from Menu) MenuItems

Gets a value indicating the collection of MenuItem objects associated with the menu.

(Inherited from Menu) Name

Gets or sets the name of the Menu.

(Inherited from Menu) RightToLeft

Gets or sets whether the text displayed by the control is displayed from right to left.

Gets or sets the ISite of the Component.

(Inherited from Component) Tag

Gets or sets user-defined data associated with the control.

(Inherited from Menu)

Methods

Creates a new MainMenu that is a duplicate of the current MainMenu.

Copies the Menu that is passed as a parameter to the current Menu.

(Inherited from Menu) CreateMenuHandle()

Creates a new handle to the 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) Dispose()

Releases all resources used by the Component.

(Inherited from Component) Dispose(Boolean)

Disposes of the resources, other than memory, used by the MainMenu.

Determines whether the specified object is equal to the current object.

(Inherited from Object) FindMenuItem(Int32, IntPtr)

Gets the MenuItem that contains the value specified.

(Inherited from Menu) FindMergePosition(Int32)

Returns the position at which a menu item should be inserted into the menu.

(Inherited from Menu) GetContextMenu()

Gets the ContextMenu that contains this menu.

(Inherited from Menu) GetForm()

Gets the Form that contains this control.

Serves as the default hash function.

(Inherited from Object) GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject) GetMainMenu()

Gets the MainMenu that contains this menu.

(Inherited from Menu) GetService(Type)

Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component) GetType()

Gets the Type of the current instance.

(Inherited from Object) InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject) MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject) MergeMenu(Menu)

Merges the MenuItem objects of one menu with the current menu.

(Inherited from Menu) OnCollapse(EventArgs)

Raises the Collapse event.

Processes a command key.

(Inherited from Menu) ToString()

Returns a string that represents the MainMenu.

Events

Occurs when the main menu collapses.

Occurs when the component is disposed by a call to the Dispose() method.

BestProg

Пример создания меню в C#. Элемент управления menuStrip

Содержание

Поиск на других ресурсах:

Условие задачи

Создать приложение типа Windows Forms Application . На форме приложения создать меню по образцу, как показано на рисунке 1.

Рис. 1. Меню, которое нужно создать

Выполнение

1. Запустить Microsoft Visual Studio. Создать проект по шаблону Windows Forms Application

Подробный пример создания проекта по шаблону Windows Forms Application описывается здесь .

Сохранить проект под произвольным именем.

2. Элемент управления MenuStrip

Для создания меню используется элемент управления MenuStrip . Он размещается на панели Toolbox во вкладке « Menus&Toolbars » (рис. 2).

Рис. 2. Элемент управления MenuStrip

После вынесения компонента на форму (с помощью мышки) форма приложения примет вид, как показано на рисунке 3. В нижней части окна проектирования формы размещается объект с именем menuStrip1 . С помощью этого имени можно иметь доступ к свойствам и методам меню.

Рис. 3. Форма приложения после размещения компонента MenuStrip

Если навести курсор мыши на элемент меню TypeHere , то появится кнопка вызова всплывающего меню. Если раскрыть всплывающее меню (клик мышкой), то откроется возможность выбора одного из трех видов элементов управления в меню (рис. 4):

  • MenuItem – стандартный элемент меню;
  • ComboBox – элемент меню типа «нисходящий список»;
  • TextBox – элемент меню типа «поле ввода».

В нашем случае выбираем первый вариант MenuItem .

Рис. 4. Типы элементов меню

Для создания подменю File достаточно набрать текст « File » (рис. 5). С помощью мышки и клавиатуры, можно добавлять элементы меню. Для удаления элемента меню, его предварительно нужно выделить мышкой и нажать клавишу Delete .

Рис. 5. Создание подменю File

После создания всех элементов меню, форма приложения примет вид, как показано на рисунке 6.

Рис. 6. Форма приложения после создания меню

Читайте также:  Windows disable automatic restart system failure

Следующими шагами есть программирование событий, связанных с выбором конкретного элемента меню.

Menu Класс

Определение

Представляет базовые возможности всех меню. Represents the base functionality for all menus.

Этот класс недоступен в .NET Core 3.1 и более поздних версиях. This class is not available in .NET Core 3.1 and later versions. Вместо него следует использовать ToolStripDropDown и ToolStripDropDownMenu, которые заменяют и расширяют элемент управления Menu. Use ToolStripDropDown and ToolStripDropDownMenu instead, which replace and extend the Menu control.

Примеры

В следующем примере кода производный класс используется MenuItem для создания структуры меню для формы. The following code example uses the derived class, MenuItem, to create a menu structure for a form. В примере кода добавляется MenuItem для представления пункта меню верхнего уровня, добавляется к нему элемент подменю для выбора размера шрифта, а затем в этот пункт меню добавляются два элемента подменю, представляющие крупные и малые шрифты в приложении. The example code adds a MenuItem to represent the top-level menu item, adds a submenu item to it for selecting a font size, and then adds two submenu items to that menu item that represent large and small font choices in an application. В этом примере требуется наличие MainMenu объекта с именем mainMenu1 и четырех MenuItem объектов с именами menuItem1 , menuItem2 , menuItem3 и menuItem4 . The example requires that there is a MainMenu object named mainMenu1 and four MenuItem objects named menuItem1 , menuItem2 , menuItem3 , and menuItem4 .

Комментарии

Этот класс недоступен в .NET Core 3.1 и более поздних версиях. This class is not available in .NET Core 3.1 and later versions. Взамен используйте и . Use and instead.

Этот класс является базовым классом для MainMenu MenuItem классов, и ContextMenu . This class is the base class for the MainMenu, MenuItem, and ContextMenu classes. Нельзя создать экземпляр этого класса. You cannot create an instance of this class. Меню приложения состоит из MenuItem объектов. The menus for an application consist of MenuItem objects. Они могут содержать другие MenuItem объекты, представляющие элементы подменю. These can contain other MenuItem objects, representing submenu items. MenuItemОбъекты могут храниться в MainMenu для вывода в виде всей структуры меню формы или ContextMenu , которая используется для вывода контекстных меню. The MenuItem objects can be stored in a MainMenu for display as an entire menu structure for a form or a ContextMenu that is used to display shortcut menus. Этот класс предоставляет функциональные возможности, общие для всех классов меню. This class provides functionality that is common for all the menu classes.

В отличие от многих базовых классов, Menu класс использует производные классы для определения многих его свойств. Unlike many base classes, the Menu class uses its derived classes to define many of its properties. Если вы используете меню в приложении многодокументного интерфейса (MDI), можно использовать MdiListItem свойство, чтобы указать MenuItem , который отображает список открытых дочерних форм MDI в приложении. If you are using your menu in a multiple-document interface (MDI) application, you can use the MdiListItem property to specify a MenuItem that displays a list of open MDI child forms in your application. MenuItemsСвойство содержит список MenuItem объектов, хранящихся в классе меню. The MenuItems property contains a list of MenuItem objects stored in the menu class. Для MainMenu или ContextMenu это свойство содержит все MenuItem отображаемые объекты. For a MainMenu or ContextMenu, this property contains all the MenuItem objects that are displayed. Для MenuItem MenuItems свойство представляет связанные с ним элементы вложенного меню. For a MenuItem, the MenuItems property represents the submenu items associated with it.

Помимо свойств, предоставляемых для всех производных классов меню, Menu класс также предоставляет методы, такие как CloneMenu и MergeMenu , которые позволяют создавать новые меню из существующих меню, а также объединять две структуры меню. In addition to the properties that are provided for all the derived menu classes, the Menu class also provides methods, such as CloneMenu and MergeMenu, that enable you to create new menus from existing menus, and also merge two menu structures together.

MenuКласс также определяет вложенный класс Menu.MenuItemCollection . The Menu class also defines the nested class Menu.MenuItemCollection. Этот класс определяет коллекцию объектов, MenuItem используемых MenuItems свойством. This class defines the collection of MenuItem objects used by the MenuItems property. Методы класса можно использовать Menu.MenuItemCollection для добавления и удаления пунктов меню из MainMenu , ContextMenu или MenuItem . You can use the methods of the Menu.MenuItemCollection class to add and remove menu items from a MainMenu, ContextMenu, or MenuItem.

Читайте также:  Обои нового mac os

Конструкторы

Инициализирует новый экземпляр класса Menu. Initializes a new instance of the Menu class.

Указывает, что метод FindMenuItem(Int32, IntPtr) должен выполнять поиск дескриптора. Specifies that the FindMenuItem(Int32, IntPtr) method should search for a handle.

Указывает, что метод FindMenuItem(Int32, IntPtr) должен выполнять поиск ярлыка. Specifies that the FindMenuItem(Int32, IntPtr) method should search for a shortcut.

Свойства

Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.

(Унаследовано от Component) Container

Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.

(Унаследовано от Component) DesignMode

Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.

(Унаследовано от Component) Events

Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.

(Унаследовано от Component) Handle

Получает значение, представляющее дескриптор окна для меню. Gets a value representing the window handle for the menu.

Получает значение, показывающее, содержит ли это меню какие-нибудь элементы меню. Gets a value indicating whether this menu contains any menu items. Это свойство доступно только для чтения. This property is read-only.

Получает значение, указывающее объект MenuItem, используемый для отображения списка дочерних форм многодокументного интерфейса (MDI). Gets a value indicating the MenuItem that is used to display a list of multiple document interface (MDI) child forms.

Получает значение, показывающее коллекцию объектов MenuItem, связанных с данным меню. Gets a value indicating the collection of MenuItem objects associated with the menu.

Возвращает или задает имя таблицы для объекта Menu. Gets or sets the name of the Menu.

Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.

(Унаследовано от Component) Tag

Получает или задает определяемые пользователем данные, связанные с элементом управления. Gets or sets user-defined data associated with the control.

Методы

Копирует объект Menu, передаваемый в качестве параметра в текущий объект Menu. Copies the Menu that is passed as a parameter to the current Menu.

Создает новый дескриптор для объекта Menu. Creates a new handle to the Menu.

Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Унаследовано от MarshalByRefObject) Dispose()

Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.

(Унаследовано от Component) Dispose(Boolean)

Уничтожает ресурсы (кроме памяти), используемые классом Menu. Disposes of the resources, other than memory, used by the Menu.

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) FindMenuItem(Int32, IntPtr)

Получает объект MenuItem, содержащий указываемое значение. Gets the MenuItem that contains the value specified.

Возвращает позицию меню, в которую должен быть вставлен элемент меню. Returns the position at which a menu item should be inserted into the menu.

Получает объект ContextMenu, содержащий это меню. Gets the ContextMenu that contains this menu.

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetLifetimeService()

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) GetMainMenu()

Получает объект MainMenu, содержащий это меню. Gets the MainMenu that contains this menu.

Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.

(Унаследовано от Component) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) InitializeLifetimeService()

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) MemberwiseClone(Boolean)

Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.

(Унаследовано от MarshalByRefObject) MergeMenu(Menu)

Объединяет объекты MenuItem одного меню с текущим меню. Merges the MenuItem objects of one menu with the current menu.

Обрабатывает клавишу для команд. Processes a command key.

Возвращает объект String, который представляет элемент управления Menu. Returns a String that represents the Menu control.

События

Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.

Оцените статью