Electron如何实现系统托盘?

344 阅读1分钟

"Electron 提供了 Tray 模块来实现系统托盘功能。首先,我们需要创建一个 Tray 实例,并指定托盘图标的路径。然后,我们可以设置托盘图标的提示信息。接着,可以监听点击事件,以实现点击托盘图标展示菜单或执行相应操作的功能。最后,不要忘记在应用关闭时销毁托盘实例。

const { app, Tray, Menu } = require('electron');
const path = require('path');

let tray = null;
app.on('ready', () => {
  tray = new Tray(path.join(__dirname, 'tray-icon.png'));
  tray.setToolTip('My Electron App');

  const contextMenu = Menu.buildFromTemplate([
    { label: 'Item 1', type: 'normal', click: () => { console.log('Clicked Item 1'); } },
    { label: 'Item 2', type: 'normal', click: () => { console.log('Clicked Item 2'); } },
    { type: 'separator' },
    { label: 'Quit', type: 'normal', click: () => { app.quit(); } }
  ]);

  tray.setContextMenu(contextMenu);

  tray.on('click', () => {
    console.log('Tray icon clicked');
    // Add logic here to show/hide window or perform other actions
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    if (tray) tray.destroy();
    app.quit();
  }
});

以上代码演示了在 Electron 应用中实现系统托盘的基本步骤:创建 Tray 实例、设置提示信息、添加菜单、监听点击事件并执行相应逻辑,最后在应用关闭时销毁托盘实例。"