# 菜单创建和事件绑定
[TOC]
新建menu.js
~~~
// 这里BrowserWindow在主线程
const {Menu, BrowserWindow} = require('electron')
var template = [
{
label: '菜单1',
submenu: [
{
label: '鸡蛋',
accelerator:'ctrl+n',//添加快捷键
click: () => {
win = new BrowserWindow({
width: 500,
height: 500,
webPreferences: {nodeIntegration: true}
})
win.loadFile('renderer/yellow.html')
win.on('closed', () => {
win = null
})
}
},
{label: '牛奶'}
]
},
{
label: '菜单2',
submenu: [
{label: '面条'},
{label: '混沌'}
]
}
]
var m = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(m)
~~~
修改main.js
添加代码:require('./menu.js')
~~~
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true // 使用remote模块
}
})
require('./menu.js')
win.loadFile('renderer/demo2.html')
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
~~~