admin 管理员组

文章数量: 1086865

electron Tray 随记

所用electron版本 7.1.11、10.1.5

const { app, BrowserWindow, nativeImage, Tray } = require('electron')
const path = require('path')app.on('ready', () => {// tray需要在ready后使用setTray()
})// 需要在全局申明,否则会出现tray消失的bug
let appTray = null/*** 同目录下建议放置 以兼容不同分辨率显示器下使用* icon.png (16*16)* icon@1.25x.png* icon@1.33x.png* icon@1.4x.png* icon@1.5x.png* icon@1.8x.png* icon@2x.png* icon@2.5x.png* icon@3x.png* icon@4x.png* icon@5x.png*/
let trayIconPath = 'tray图标所在路径' // 如 path.join(__dirname, './trayIcon/icon.png')
function setTray () {let image = nativeImage.createFromPath(trayIconPath)appTray = new Tray(image)appTray.on('click', async () => {// 点击tray图标时触发,一般习惯点击后显示应用BrowserWindow.getAllWindows().show()})if (global.process.platform !== 'darwin') {// setToolTip 仅在win上显示, 在mac上使用不会报错但也没有效果的样子appTray.setToolTip('鼠标移入显示文本')/** * tray设置contextmenu后,在mac端的click事件将会无效* 为了表现与其他应用一致,不在mac上设置该属性* 在mac上可以右键程序坞上的应用图标关闭应用*/const contextMenu = Menu.buildFromTemplate([{label: '退出应用',click: async () => {app.quit()}}])appTray.setContextMenu(contextMenu)}
}

本文标签: electron Tray 随记