electron创建菜单有两种方式,一种是通过菜单模板创建菜单,一种是通过MenuItem动态创建菜单项
之前写过如何通过菜单模板创建菜单:https://www.zhiboblog.com/1318.html
下面来介绍一下如何通过MenuItem动态创建菜单项:
首先需要引入Menu模块和MenuItem模块,然后new MenuItem()创建菜单项,menu.append()将菜单项添加进去,最后Menu.setApplicationMenu(menu)设置菜单
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const Menu = electron.Menu;
const MenuItem = electron.MenuItem;
function createWindow(){
win = new BrowserWindow({
show:false,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
const menu = new Menu();
var menuChildItem1 = new MenuItem({label:'打开',click:()=>{}});//创建一个子菜单项
var menuChildItem2 = new MenuItem({label:'保存',click:()=>{}});//创建一个子菜单项
var menuItem1 = new MenuItem({label:'文件',submenu:[menuChildItem1,menuChildItem2]});//创建一个顶级菜单项,将子菜单项添加进去
var menuChildItem3 = new MenuItem({label:'复制',click:()=>{}});//创建一个子菜单项
var menuChildItem4 = new MenuItem({label:'粘贴',click:()=>{}});//创建一个子菜单项
var menuItem2 = new MenuItem({label:'编辑',submenu:[menuChildItem3,menuChildItem4]});//创建一个顶级菜单项,将子菜单项添加进去
menu.append(menuItem1);//将菜单项添加到menu中
menu.append(menuItem2);//将菜单项添加到menu中
Menu.setApplicationMenu(menu);//将菜单设置到应用上
win.on('ready-to-show',()=>{
win.show();
});
win.on('closed',()=>{
console.log('closed');
win = null;
});
//打开开发者工具
win.webContents.openDevTools();
}
app.allowRendererProcessReuse = true;
app.on('ready',createWindow);
app.on('window-all-closed',()=>{
console.log('window-all-closed');
if(process.platform != 'darwin'){
app.quit();
}
});
app.on('activate',()=>{
console.log('activate');
if(win == null) {
createWindow();
}
});
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const Menu = electron.Menu;
const MenuItem = electron.MenuItem;
function createWindow(){
win = new BrowserWindow({
show:false,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
const menu = new Menu();
var menuChildItem1 = new MenuItem({label:'打开',click:()=>{}});//创建一个子菜单项
var menuChildItem2 = new MenuItem({label:'保存',click:()=>{}});//创建一个子菜单项
var menuItem1 = new MenuItem({label:'文件',submenu:[menuChildItem1,menuChildItem2]});//创建一个顶级菜单项,将子菜单项添加进去
var menuChildItem3 = new MenuItem({label:'复制',click:()=>{}});//创建一个子菜单项
var menuChildItem4 = new MenuItem({label:'粘贴',click:()=>{}});//创建一个子菜单项
var menuItem2 = new MenuItem({label:'编辑',submenu:[menuChildItem3,menuChildItem4]});//创建一个顶级菜单项,将子菜单项添加进去
menu.append(menuItem1);//将菜单项添加到menu中
menu.append(menuItem2);//将菜单项添加到menu中
Menu.setApplicationMenu(menu);//将菜单设置到应用上
win.on('ready-to-show',()=>{
win.show();
});
win.on('closed',()=>{
console.log('closed');
win = null;
});
//打开开发者工具
win.webContents.openDevTools();
}
app.allowRendererProcessReuse = true;
app.on('ready',createWindow);
app.on('window-all-closed',()=>{
console.log('window-all-closed');
if(process.platform != 'darwin'){
app.quit();
}
});
app.on('activate',()=>{
console.log('activate');
if(win == null) {
createWindow();
}
});