# 菜單創建和事件綁定
[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()
}
})
~~~