electron 教程【7】如何实现自定义应用程序菜单,和右键菜单

您所在的位置:网站首页 应用程序的菜单栏 electron 教程【7】如何实现自定义应用程序菜单,和右键菜单

electron 教程【7】如何实现自定义应用程序菜单,和右键菜单

2024-07-16 18:38| 来源: 网络整理| 查看: 265

一、实现自定义应用程序菜单

基本思路:自定义应用程序菜单,然后将该菜单设置到对应的window上。

如何操作:Menu和MenuItem模块分别对应菜单,和菜单的内容。可以直接在主进程中调用,也可以在渲染进程中通过remote模块调用。

一个示例:

const electron = require('electron') const BrowserWindow = electron.BrowserWindow const Menu = electron.Menu const app = electron.app var template = [{ label: '编辑', submenu: [{ label: '撤销', accelerator: 'CmdOrCtrl+Z', role: 'undo' }, { label: '重做', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' }, { type: 'separator' }, { label: '复制', accelerator: 'CmdOrCtrl+C', role: 'copy' }, { label: '粘贴', accelerator: 'CmdOrCtrl+V', role: 'paste' }] }, { label: '帮助', role: 'help', submenu: [{ label: '学习更多', click: function () { electron.shell.openExternal('http://electron.atom.io') } }] }]; function createWindow () { // Create the browser window. mainWindow = new BrowserWindow({width: 800, height: 600}) // Set menu to window const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) } app.on('ready', createWindow) // Quit when all windows are closed. app.on('window-all-closed', function () { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', function () { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) { createWindow() } })

一、实现右键菜单

基本思路:自定义右键菜单内容,然后在按下鼠标右键时,在渲染进程中发送信号,在主进程中显示右键菜单。

如何操作:Menu和MenuItem模块分别对应菜单,和菜单的内容。可以直接在主进程中调用,也可以在渲染进程中通过remote模块调用。

一个示例:

渲染进程:

$('body').mouseup( (event) => { var e = event || window.event; let nType = e.button; if (2 === nType) { showRightClickMenu(); } e.stopPropagation(); } ); function showRightClickMenu(){ ipcRenderer.send('sigShowRightClickMenu'); }

主进程:

ipcMain.on('sigShowRightClickMenu', (event) => { //! 生成菜单 const menu = new Menu(); menu.append(new MenuItem({ label: 'Hello world' })); menu.append(new MenuItem({ type: 'separator' })); menu.append(new MenuItem({ label: 'Electron', click: () => { Electron.shell.openExternal('https://www.baidu.com'); } }) ); const win = BrowserWindow.fromWebContents(event.sender); menu.popup(win); });


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3