Electron【详解】菜单 Menu
顶部菜单
因顶部菜单款式传统,且不同系统的配置不同,建议在页面中自行实现菜单,而不采用 Electron 自带的菜单方案。
主进程中
import { Menu } from 'electron'
const template = [{ role: 'appMenu' }]
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
在 template 中添加菜单配置项即可。
- role 为系统内置的菜单,更多系统菜单如:
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' }, // 我是分割线,不是菜单
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
自定义菜单
自定义菜单名称 label
{
label: '自定义菜单',
submenu: [{ role: 'minimize' }]
}
自定义菜单方法 click 和 快捷键 accelerator
{
label: '自定义菜单',
submenu: [
{
label: 'electron 官网',
click: async () => {
// 会用默认浏览器打开electron 官网
await shell.openExternal('https://electronjs.org')
},
accelerator: 'CmdOrCtrl+1' // 快捷键
}
]
}
自定义菜单类型 type
分割线
{ type: 'separator' }
单选
{
label: '菜单位置',
submenu: [
{
type: 'radio',
label: '顶部',
click: () => {
// 省略了实现逻辑
}
},
{
type: 'radio',
label: '底部',
click: () => {
// 省略了实现逻辑
}
}
]
}
多选
{
label: '自定义菜单',
submenu: [
{
type: 'checkbox',
label: '显示工具栏',
click: (e) => {
// 省略了实现逻辑
console.log(e.checked)
}
}
]
}
专门针对 mac 系统配置菜单
const isMac = process.platform === 'darwin'
const template = [
...(isMac
? [
{
label: 'mac系统菜单',
submenu: [{ role: 'quit' }]
}
]
: [
{
label: '其他系统菜单',
submenu: [{ role: 'quit' }]
}
])
]
动态改变菜单
import { Menu, MenuItem } from 'electron'
const template = [
{
id: 'customMenu',
label: '自定义菜单',
submenu: [
{
id: 'customMenu-oldWeb',
label: 'electron 官网',
click: async () => {
// 隐藏原菜单项
menu.getMenuItemById('customMenu-oldWeb')!.visible = false
// 创建新菜单项
const newMenuItem = new MenuItem({
id: 'customMenu-newWeb',
label: 'electron 官网(新)',
click: async () => {
await shell.openExternal('https://electronjs.org')
},
accelerator: 'CmdOrCtrl+2' // 快捷键
})
// 将新菜单项添加到原菜单项的子菜单中
menu.getMenuItemById('customMenu')?.submenu?.append(newMenuItem)
// 更新菜单
Menu.setApplicationMenu(menu)
},
accelerator: 'CmdOrCtrl+1' // 快捷键
}
]
}
]
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
清空菜单
Menu.setApplicationMenu(null)
任务栏菜单
- Mac 系统
- Windows 系统
右键菜单
见 https://blog.csdn.net/weixin_41192489/article/details/144611858