tray.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const {app, Tray, Menu} = require('electron');
  3. const path = require('path');
  4. const helper = require('./helper');
  5. const config = require('../config');
  6. /**
  7. * 安装模块
  8. */
  9. exports.setup = function () {
  10. console.log('[electron-lib-tray] [setup]');
  11. const cfg = config.get('tray');
  12. // 托盘图标
  13. let iconPath = path.join(app.getAppPath(), cfg.icon);
  14. // 托盘菜单功能列表
  15. let trayMenuTemplate = [
  16. {
  17. label: '显示',
  18. click: function () {
  19. MAIN_WINDOW.show();
  20. }
  21. },
  22. {
  23. label: '退出',
  24. click: function () {
  25. helper.appQuit();
  26. }
  27. }
  28. ]
  29. // 点击关闭,最小化到托盘
  30. MAIN_WINDOW.on('close', (event) => {
  31. if (!CAN_QUIT) {
  32. MAIN_WINDOW.hide();
  33. MAIN_WINDOW.setSkipTaskbar(true);
  34. event.preventDefault();
  35. }
  36. });
  37. MAIN_WINDOW.show();
  38. APP_TRAY = new Tray(iconPath);
  39. APP_TRAY.setToolTip(cfg.title); // 托盘标题
  40. const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
  41. APP_TRAY.setContextMenu(contextMenu);
  42. // 监听 显示/隐藏
  43. APP_TRAY.on('click', function(){
  44. if (MAIN_WINDOW.isVisible()) {
  45. MAIN_WINDOW.hide();
  46. MAIN_WINDOW.setSkipTaskbar(false);
  47. } else {
  48. MAIN_WINDOW.show();
  49. MAIN_WINDOW.setSkipTaskbar(true);
  50. }
  51. });
  52. return APP_TRAY;
  53. }
  54. exports = module.exports;