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 子模块创建了托盘。 然后,我们使用模板创建了一个菜单,并进一步将菜单附加到我们的托盘对象。

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

$ electron ./main.js

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

tray