Electron 系统托盘
系统托盘是应用程序窗口之外的菜单。在 MacOS 和 Ubuntu 上,它位于屏幕的右上角。在 Windows 上,它位于右下角。我们可以使用 Electron 在系统托盘中为我们的应用程序创建菜单。
创建一个新的
main.js 文件并向其中添加以下代码。准备一个可用于系统托盘图标的 png 文件。
const {app, BrowserWindow} = 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
}))
}
app.on('ready', createWindow)
设置基本浏览器窗口后,我们将创建一个新的
index.html 文件,内容如下-
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Menus</title>
</head>
<body>
<script type = "text/javascript">
const {remote} = require('electron')
const {Tray, Menu} = remote
const path = require('path')
let trayIcon = new Tray(path.join('','/home/ayushgp/Desktop/images.png'))
const trayMenuTemplate = [
{
label: 'Empty Application',
enabled: false
},
{
label: 'Settings',
click: function () {
console.log("Clicked on settings")
}
},
{
label: 'Help',
click: function () {
console.log("Clicked on Help")
}
}
]
let trayMenu = Menu.buildFromTemplate(trayMenuTemplate)
trayIcon.setContextMenu(trayMenu)
</script>
</body>
</html>
我们使用 Tray 子模块创建了托盘。然后我们使用模板创建了一个菜单,并进一步将菜单附加到我们的托盘对象上。
使用以下命令运行应用程序-
当您运行上述命令时,请检查您的系统托盘中是否有您使用的图标。我在我的申请中使用了笑脸。上面的命令将生成以下输出-
