tray.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { Tray, Menu } from 'electron';
  2. import { join } from 'path';
  3. import { getBaseDir } from 'ee-core/ps';
  4. import { logger } from 'ee-core/log';
  5. import { app as electronApp } from 'electron';
  6. import { getMainWindow, getCloseAndQuit, setCloseAndQuit } from 'ee-core/electron';
  7. /**
  8. * 托盘
  9. * @class
  10. */
  11. class TrayService {
  12. constructor() {
  13. this.tray = null;
  14. this.config = {
  15. title: 'electron-egg',
  16. icon: '/public/images/tray.png'
  17. }
  18. }
  19. /**
  20. * 创建托盘
  21. */
  22. create () {
  23. logger.info('[tray] load');
  24. const cfg = this.config;
  25. const mainWindow = getMainWindow();
  26. // tray icon
  27. const iconPath = join(getBaseDir(), cfg.icon);
  28. // 托盘菜单功能列表
  29. const trayMenuTemplate = [
  30. {
  31. label: '显示',
  32. click: function () {
  33. mainWindow.show();
  34. }
  35. },
  36. {
  37. label: '退出',
  38. click: function () {
  39. electronApp.quit();
  40. }
  41. }
  42. ]
  43. // 设置一个标识,点击关闭,最小化到托盘
  44. setCloseAndQuit(false);
  45. mainWindow.on('close', (event) => {
  46. if (getCloseAndQuit()) {
  47. return;
  48. }
  49. mainWindow.hide();
  50. event.preventDefault();
  51. });
  52. // 实例化托盘
  53. this.tray = new Tray(iconPath);
  54. this.tray.setToolTip(cfg.title);
  55. const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
  56. this.tray.setContextMenu(contextMenu);
  57. // 左键单击的时候能够显示主窗口
  58. this.tray.on('click', () => {
  59. mainWindow.show()
  60. })
  61. }
  62. }
  63. TrayService.toString = () => '[class TrayService]';
  64. export const trayService = new TrayService();