Electron Windows增加托盘悬浮框功能
背景
在做Electron Windows 桌面应用时候,做鼠标悬浮到托盘图标上时显示一个悬浮框(例如做消息提醒),但因为Windows没有提供托盘mouse-enter/mouse-leave事件,无法直接做这个功能,考虑到还有mouse-move事件,弄个间接的方式实现。
实现步骤
1、监听mouse-move事件,当触发时,即也相当触发mouse-enter事件。
2、开始定时(100ms)获取托盘位置和鼠标位置,判断鼠标是否还在托盘图标里,当已不在时,触发mouse-leave事件并停止定时查询。
//判断鼠标是否还在托盘图标
trayBounds = tray.getBounds();
point = screen.getCursorScreenPoint();
if(!(trayBounds.x < point.x && trayBounds.y < point.y && point.x < (trayBounds.x + trayBounds.width) && point.y < (trayBounds.y + trayBounds.height))){
//已不在托盘,触发mouse-leave
}
3、当mouse-enter时,显示悬浮窗口到托盘上方,当mouse-enter,隐藏悬浮窗口。
PS:悬浮窗口需要设置置顶属性,且不显示在任务栏。
vi设计http://www.maiqicn.com 办公资源网站大全https://www.wode007.com
具体代码
var leaveInter,
trayBounds,
point,
isLeave = true;
function checkTrayLeave(){
clearInterval(leaveInter)
leaveInter = setInterval(function(){
trayBounds = tray.getBounds();
point = screen.getCursorScreenPoint();
if(!(trayBounds.x < point.x && trayBounds.y < point.y && point.x < (trayBounds.x + trayBounds.width) && point.y < (trayBounds.y + trayBounds.height))){
//触发mouse-leave
clearInterval(leaveInter);
isLeave = true;
}
}, 100)
}
tray.on('mouse-move', () => {
if (isLeave) {
//触发mouse-enter
isLeave = false;
checkTrayLeave();
}
})
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~