- Electron 教程
- Electron - 首页
- Electron - 概览
- Electron - 安装
- Electron 如何运作?
- Electron - Hello World
- Electron - 构建 UI
- Electron - 文件处理
- Electron - 原生 Node 类库
- 进程间通信(IPC)
- Electron - 系统对话框
- Electron - 菜单
- Electron - 系统托盘
- Electron - 通知
- Electron - Webview
- Electron - 音频和视频捕获
- Electron - 定义快捷键
- Electron - 环境变量
- Electron - 调试
- Electron - 打包应用
- Electron - 资源
- Electron 有用资源
- Electron - 快速指南
- Electron - 有用资源
- Electron - 讨论
Electron - 菜单
桌面应用带有两种类型的菜单 – 应用程序菜单(在顶部栏)和 上下文菜单(右键菜单)。本章我们将学习如何创建这两个菜单。
我们将使用两个模块 – Menu 和 MenuItem 模块。注意,Menu 和 MenuItem 模块仅在主进程中可用。要在渲染器进程中使用这些模块,你需要 remote 模块。当我们创建一个上下文菜单时会用到它。
现在,让我们为 Electron 主进程创建一个新的 main.js 文件 −
const {app, BrowserWindow, Menu, MenuItem} = require('electron')
const url = require('url')
const path = require('path')
let win
function createWindow() {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(url.format ({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
}
const template = [
{
label: 'Edit',
submenu: [
{
role: 'undo'
},
{
role: 'redo'
},
{
type: 'separator'
},
{
role: 'cut'
},
{
role: 'copy'
},
{
role: 'paste'
}
]
},
{
label: 'View',
submenu: [
{
role: 'reload'
},
{
role: 'toggledevtools'
},
{
type: 'separator'
},
{
role: 'resetzoom'
},
{
role: 'zoomin'
},
{
role: 'zoomout'
},
{
type: 'separator'
},
{
role: 'togglefullscreen'
}
]
},
{
role: 'window',
submenu: [
{
role: 'minimize'
},
{
role: 'close'
}
]
},
{
role: 'help',
submenu: [
{
label: 'Learn More'
}
]
}
]
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
app.on('ready', createWindow)
我们在这里从模板构建菜单。这意味着,我们将菜单作为 JSON 提供给函数,函数会处理剩下的工作。现在,我们必须将这个菜单设置为应用程序菜单。
现在,创建一个名为 index.html 的空 HTML 文件,并使用以下命令运行此应用程序 −
$ electron ./main.js
在应用程序菜单的正常位置,你将看到一个基于上述模板的菜单。
我们从主进程创建了这个菜单。现在,让我们为我们的应用创建一个上下文菜单。我们可以在 HTML 文件中执行此操作 −
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Menus</title>
</head>
<body>
<script type = "text/javascript">
const {remote} = require('electron')
const {Menu, MenuItem} = remote
const menu = new Menu()
// Build menu one item at a time, unlike
menu.append(new MenuItem ({
label: 'MenuItem1',
click() {
console.log('item 1 clicked')
}
}))
menu.append(new MenuItem({type: 'separator'}))
menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true}))
menu.append(new MenuItem ({
label: 'MenuItem3',
click() {
console.log('item 3 clicked')
}
}))
// Prevent default action of right click in chromium. Replace with our menu.
window.addEventListener('contextmenu', (e) => {
e.preventDefault()
menu.popup(remote.getCurrentWindow())
}, false)
</script>
</body>
</html>
我们使用 remote 模块导入了 Menu 和 MenuItem 模块;然后,我们创建了一个菜单,并将我们的菜单项一个个附加到它。此外,我们阻止了 Chromium 中右键的默认动作,并用自己的菜单替换了它。
在 Electron 中创建菜单是一项非常简单的任务。现在,你可以将事件处理程序附加到这些项,并根据需要处理事件。
广告