Electron 教程:系统托盘
系统托盘是应用程序窗口之外的菜单。在MacOS和Ubuntu上,它位于你屏幕的右上角。在窗户上,它在右下角。我们可以使用电子在系统托盘中为我们的应用程序创建菜单。
为系统托盘图标准备一个png文件,创建一个新的main.js文件,并向其中添加以下代码。
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模块创建了系统托盘。然后,我们使用模板创建了一个菜单,并进一步将该菜单附加到tray对象上。
使用以下命令运行应用程序
$ electron ./main.js
当我们执行上述命令后,请检查系统托盘中您使用的图标。我的应用程序使用了笑脸。上述命令将产生以下输出.
