Electron - System Tray

系统托盘是应用程序窗口之外的菜单.在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子模块创建了托盘.然后,我们使用模板创建了一个菜单,并进一步将菜单附加到托盘对象.

使用以下命令运行应用程序 :

$ electron ./main.js

运行上述命令时,请检查系统托盘中是否有您使用的图标.我的笑脸用于我的申请.上面的命令将生成以下输出 :

tray