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

Menu

Класс: Menu

Создайте меню приложения и контекстное меню.

Process: Main

new Menu()

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

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

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

  • menu Menu | null

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

Также на 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 proceeding &. 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, Window and Help.

Возвращает 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.

  • 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.

  • template (MenuItemConstructorOptions | MenuItem)[]

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.

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

Closes the context menu in the window.

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

  • id string

Возвращает элемент MenuItem с указанным 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

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

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

Возвращает:

  • Событие типа event

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

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

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

Массив MenuItem[] содержит элементы меню.

Each Menu consists of multiple MenuItems and each MenuItem can have a submenu.

Примеры

An example of creating the application menu with the simple template API:

const { app, Menu } = require('electron')

const isMac = process.platform === 'darwin'

const template = [
// { role: 'appMenu' }
...(isMac
? [{
label: app.name,
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' }
]
}]
: []),
// { role: 'fileMenu' }
{
label: 'File',
submenu: [
isMac ? { role: 'close' } : { role: 'quit' }
]
},
// { role: 'editMenu' }
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
...(isMac
? [
{ role: 'pasteAndMatchStyle' },
{ role: 'delete' },
{ role: 'selectAll' },
{ type: 'separator' },
{
label: 'Speech',
submenu: [
{ role: 'startSpeaking' },
{ role: 'stopSpeaking' }
]
}
]
: [
{ role: 'delete' },
{ type: 'separator' },
{ role: 'selectAll' }
])
]
},
// { role: 'viewMenu' }
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forceReload' },
{ role: 'toggleDevTools' },
{ type: 'separator' },
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' }
]
},
// { role: 'windowMenu' }
{
label: 'Window',
submenu: [
{ role: 'minimize' },
{ role: 'zoom' },
...(isMac
? [
{ type: 'separator' },
{ role: 'front' },
{ type: 'separator' },
{ role: 'window' }
]
: [
{ role: 'close' }
])
]
},
{
role: 'help',
submenu: [
{
label: 'Learn More',
click: async () => {
const { shell } = require('electron')
await shell.openExternal('https://electronjs.org')
}
}
]
}
]

const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)

Графический процесс

To create menus initiated by the renderer process, send the required information to the main process using IPC and have the main process display the menu on behalf of the renderer.

Below is an example of showing a menu when the user right clicks the page:

// renderer
window.addEventListener('contextmenu', (e) => {
e.preventDefault()
ipcRenderer.send('show-context-menu')
})

ipcRenderer.on('context-menu-command', (e, command) => {
// ...
})

// main
ipcMain.on('show-context-menu', (event) => {
const template = [
{
label: 'Menu Item 1',
click: () => { event.sender.send('context-menu-command', 'menu-item-1') }
},
{ type: 'separator' },
{ label: 'Menu Item 2', type: 'checkbox', checked: true }
]
const menu = Menu.buildFromTemplate(template)
menu.popup({ window: BrowserWindow.fromWebContents(event.sender) })
})

Замечания о меню приложения в macOS

macOS has a completely different style of application menu from Windows and Linux. Here are some notes on making your app's menu more native-like.

Стандартные меню

On macOS there are many system-defined standard menus, like the Services and Windows menus. Чтобы сделать меню стандартным меню, Вы должны установить значение role у меню в одно из следующих, а Electron распознает их и сделает их стандартным меню:

  • window
  • help
  • services

Действия элементов стандартного меню

macOS представляет стандартные действия для некоторых элементов меню, таких как About xxx, Hide xxx и Hide Others. Чтобы установить действие элемента меню на стандартное действие, Вы должны установить атрибут role элемента меню.

Имя главного меню

На macOS название первого элемента меню приложения - всегда название Вашего приложения, независимо от того, какое название элемента Вы установили. Чтобы изменить его, измените файл Info.plist Вашей сборки приложения. See About Information Property List Files for more information.

Menu sublabels, or subtitles, can be added to menu items using the sublabel option. Below is an example based on the renderer example above:

// main
ipcMain.on('show-context-menu', (event) => {
const template = [
{
label: 'Menu Item 1',
sublabel: 'Subtitle 1',
click: () => { event.sender.send('context-menu-command', 'menu-item-1') }
},
{ type: 'separator' },
{ label: 'Menu Item 2', sublabel: 'Subtitle 2', type: 'checkbox', checked: true }
]
const menu = Menu.buildFromTemplate(template)
menu.popup({ window: BrowserWindow.fromWebContents(event.sender) })
})

Настройка меню для конкретного окна браузера (Linux Windows)

The setMenu method of browser windows can set the menu of certain browser windows.

Позиция элемента меню

You can make use of before, after, beforeGroupContaining, afterGroupContaining and id to control how the item will be placed when building a menu with Menu.buildFromTemplate.

  • before - Inserts this item before the item with the specified id. Если ссылаемый элемент не существует, тогда элемент будет вставлен в конец меню. Кроме того, подразумевается, что рассматриваемый элемент меню размещен в той же "группе", что и сам элемент.
  • after - Inserts this item after the item with the specified id. Если ссылаемый элемент не существует, тогда элемент будет вставлен в конец меню. Кроме того, подразумевается, что рассматриваемый элемент меню размещен в той же "группе", что и сам элемент.
  • beforeGroupContaining - Provides a means for a single context menu to declare the placement of their containing group before the containing group of the item with the specified id.
  • afterGroupContaining - Provides a means for a single context menu to declare the placement of their containing group after the containing group of the item with the specified id.

By default, items will be inserted in the order they exist in the template unless one of the specified positioning keywords is used.

Примеры

Template:

[
{ id: '1', label: 'one' },
{ id: '2', label: 'two' },
{ id: '3', label: 'three' },
{ id: '4', label: 'four' }
]

Menu:

- 1
- 2
- 3
- 4

Template:

[
{ id: '1', label: 'one' },
{ type: 'separator' },
{ id: '3', label: 'three', beforeGroupContaining: ['1'] },
{ id: '4', label: 'four', afterGroupContaining: ['2'] },
{ type: 'separator' },
{ id: '2', label: 'two' }
]

Menu:

- 3
- 4
- ---
- 1
- ---
- 2

Template:

[
{ id: '1', label: 'one', after: ['3'] },
{ id: '2', label: 'two', before: ['1'] },
{ id: '3', label: 'three' }
]

Menu:

- ---
- 3
- 2
- 1