作者:梁棒棒托盘虽然小,但是用处很大。它是您的应用程序在操作系统中运行的标识。可以通知你有新消息,唤醒应用程序界面,设置上下文(右键)菜单可以设置更多功能等等,接下来我们将这些功能一一实现,必须要在主进程中操作.1.创建托盘首先创建一个托盘图标,简单三步:从electron库中导入Tray类获??取图标地址实例化Tray并传入图标地址代码也很简单:const{Tray}=require('electron')constpath=require('path')consticon=path.join(__dirname,'yourimagepath')newTray(icon)将创建一个系统托盘。很简单对不对,但是这个图标还没有任何功能,那我们就给图标添加一些属性和事件吧。2.设置托盘属性为托盘实例设置一些属性和事件,包括上下文菜单,鼠标移动文本。详细文档请点击此处。这里我们为托盘设置了灵活的图标,使其可以根据系统主题显示不同的图标;然后设置一个当鼠标移入图标时会显示的提示文字,最后为它设置一个上下文菜单,这样它就可以有一些功能了。先看效果图:附上代码:const{Tray,Menu,nativeTheme,BrowserWindow}=require('electron')constpath=require('path')lettray//设置top的操作和图标APP图标constlightIcon=path.join(__dirname,'..','..','resources','tray','StatusIcon_light.png')constdarkIcon=path.join(__dirname,'..','..','resources','tray','StatusIcon_dark.png')//根据系统主题显示不同的主题图标tray=newTray(nativeTheme.shouldUseDarkColors?darkIcon:lightIcon)tray.setToolTip('Electron-Playground')constcontextMenu=Menu.buildFromTemplate([{label:'打开新窗口',点击:()=>{letchild=newBrowserWindow({parent:BrowserWindow.getFocusedWindow()})child.loadURL('https://electronjs.org')child.show()},},{label:'删除图标',click:()=>{tray.destroy()},},])//设置上下文菜单tray.setContextMenu(contextMenu)想自己试试如果你有尝试,点击electron-playground。然后继续:上面我们设置托盘根据系统主题显示不同的图标,但是系统主题是动态的,具体怎么做,请看:nativeTheme.on('updated',()=>{tray.setImage(nativeTheme.shouldUseDarkColors?darkIcon:lightIcon)})只需添加一个主题侦听器事件。有关属性、事件和方法的更多列表,请参阅官方文档。3.例子简单列举几个例子。3.1显示未读消息数(macOS)在macOS系统下,可以通过setTitle(String)来设置未读消息数。PS:windows下无效果。tray.setTitle("1")的效果如下:3.2有未读消息时图标闪烁(windows)在Windows下,可以通过setImage在普通图标和空图标之间切换,实现闪烁效果。mac系统下,空图标不占图标空间,所以需要设置透明图标。可以把nativeImage.createEmpty()换成darkIcon,执行看看效果。如何判断操作系统平台,windows下效果点这里:附代码:const{Tray,Menu,BrowserWindow,nativeImage}=require('electron')constpath=require('path')lettraylettimerlettoggle=truelethaveMessage=trueconstlightIcon=path.join(__dirname,'..','..','resources','tray','StatusIcon_light.png')constdarkIcon=path.join(__dirname,'..','..','resources','tray','StatusIcon_dark.png')constwin=BrowserWindow.getFocusedWindow();tray=newTray(lightIcon)constcontextMenu=Menu.buildFromTemplate([{label:'张新闻San',点击:()=>{letchild=newBrowserWindow({parent:BrowserWindow.getFocusedWindow()})child.loadURL('https://electronjs.org')child.show()},},{type:'separator'},{label:'删除图标',click:()=>{tray.destroy()clearInterval(timer)},},])tray.setContextMenu(contextMenu)tray.setToolTip('Electron-游乐场')if(haveMessage){timer=setInterval(()=>{toggle=!toggleif(toggle){tray.setImage(nativeImage.createEmpty())}else{tray.setImage(lightIcon)}},600)}3.3双击托盘显示隐藏界面(windows)Windows效果:附代码:const{托盘,BrowserWindow}=require('electron')constpath=require('path')lettrayconstlightIcon=path.join(__dirname,'..','..','resources','tray','StatusIcon_light.png')constwin=BrowserWindow.getFocusedWindow()tray=newTray(lightIcon)tray.on('double-click',()=>{win.isVisible()?win.hide():win.show()})注意:这个效果在windows上是好的,但是在mac下会有一些问题。双击事件可能无效。实际使用过程中要注意,但是mac下一般不会用到这个事件。差不多,Segmentfault,CSDN,简书,开源中国,博客园账号。
