Перейти к основному содержанию

Menu

Класс: Menu​

Create application menus and context menus.

ProcessMain

The presentation of menus varies depending on the operating system:

  • Under Windows and Linux, menus are visually similar to Chromium.
  • Under macOS, these will be native menus.

[!TIP] See also: A detailed guide about how to implement menus in your application.

[!WARNING] Electron's built-in classes cannot be subclassed in user code. For more information, see the FAQ.

new Menu()​

Создает новое меню.

Статические методы​

Класс Menu имеет следующие статические методы:

Устанавливает меню в качестве меню приложения на macOS. On Windows and Linux, the menu will be set as each window's top menu.

On Linux, the menu bar uses GTK theme colors when GTK is available. If GTK cannot initialize, it uses Chromium's built-in light or dark menu colors, following nativeTheme.shouldUseDarkColors.

Также на Windows и Linux, Вы можете использовать & в названии подменю верхнего списка, чтобы указать, какая буква должна получить сгенерированный акселератор( Accelerator ). Для примера, использование &File для меню файла в результате сгенерирует акселератор( Accelerator ) Alt-F, который открывает соответствующее меню. The indicated character in the button label then gets an underline, and the & character is not displayed on the button label.

In order to escape the & character in an item name, add a preceding &. For example, &&File would result in &File displayed on the button label.

Passing null will suppress the default menu. On Windows and Linux, this has the additional effect of removing the menu bar from the window.

[!NOTE] The default menu will be created automatically if the app does not set one. It contains standard items such as File, Edit, View, and Window.

Возвращает Menu | null - меню приложения, если установлено, иначе null.

[!NOTE] The returned Menu instance doesn't support dynamic addition or removal of menu items. Instance properties can still be dynamically modified.

History
Version(s)Changes
None
API ADDED
  • options Object | null
    • light Object (optional) - Colors used when menus are drawn with light colors.
      • background string (optional) - Background color of the hovered or keyboard-focused menu item, as a CSS color string (e.g. #0067c0).
      • foreground string (optional) - Text color of the hovered or keyboard-focused menu item, as a CSS color string.
    • dark Object (optional) - Colors used when menus are drawn with dark colors.
      • background string (optional) - Background color of the hovered or keyboard-focused menu item, as a CSS color string.
      • foreground string (optional) - Text color of the hovered or keyboard-focused menu item, as a CSS color string.

Sets the colors used to highlight the hovered or keyboard-focused item in every menu the app shows, including context menus and the menu bar's dropdowns. Light and dark colors are set separately, and any color left unset keeps the default for that mode. Each call replaces the colors set by any previous call. Passing null restores the defaults.

const { Menu } = require('electron')

Menu.setHighlightColors({
light: { background: '#0067c0', foreground: '#ffffff' },
dark: { background: '#4cc2ff', foreground: '#000000' }
})

Menus opened after the call use the new colors. The colors are not applied while Windows high contrast mode or forced colors are active, so the user's system colors take priority.

This method has no effect on macOS and Linux.

  • action string

Посылает action первому ответчику приложения. Это используется для эмуляции поведения меню macOS. Usually you would use the role property of a MenuItem.

See the macOS Cocoa Event Handling Guide for more information on macOS' native actions.

Returns Menu

Generally, the template is an array of options for constructing a MenuItem. The usage can be referenced above.

Вы также можете прикрепить другие поля к элементу template и они станут свойствами элементов созданного меню.

Методы экземпляра​

Объект меню имеет следующие методы экземпляра:

  • options Object (опционально)
    • window BaseWindow (optional) - Default is the focused window.
    • frame WebFrameMain (optional) - Provide the relevant frame if you want certain OS-level features such as Writing Tools on macOS to function correctly. Typically, this should be params.frame from the context-menu event on a WebContents, or the focusedFrame property of a WebContents.
    • x number (optional) - Default is the current mouse cursor position. Must be declared if y is declared.
    • y number (optional) - Default is the current mouse cursor position. Must be declared if x is declared.
    • positioningItem number (optional) macOS - The index of the menu item to be positioned under the mouse cursor at the specified coordinates. Default is -1.
    • sourceType string (optional) Windows Linux - This should map to the menuSourceType provided by the context-menu event. It is not recommended to set this value manually, only provide values you receive from other APIs or leave it undefined. Can be none, mouse, keyboard, touch, touchMenu, longPress, longTap, touchHandle, stylus, adjustSelection, or adjustSelectionReset.
    • callback Функция (опционально) - вызывается, когда меню закрыто.

Pops up this menu as a context menu in the BaseWindow.

[!TIP] For more details, see the Context Menu guide.

  • window BaseWindow (optional) - Default is the focused window.

Closes the context menu in the window.

Добавляет menuItem в меню.

  • id string

Returns MenuItem | null - the item with the specified id

Вставляет menuItem в меню на позицию pos.

События экземпляра​

Объекты созданные с помощью new Menu или возвращенные из Menu.buildFromTemplate вызывают следующие события:

[!NOTE] Some events are only available on specific operating systems and are labeled as such.

Событие: 'menu-will-show'​

Возвращает:

  • event Event

Вызывается при вызове menu.popup().

Событие: 'menu-will-close'​

Возвращает:

  • event Event

Вызывается, когда всплывающее окно закрывается вручную или с помощью menu.closePopup().

Свойства экземпляра​

Объекты menu также имеют следующие свойства:

A MenuItem[] array containing the menu's items.

Each Menu consists of multiple MenuItem instances and each MenuItem can nest a Menu into its submenu property.