这是我参与8月更文挑战的第6天,活动详情查看:8月更文挑战
托盘效果
偶然看到同花顺顶部的
托盘
, 有点好奇是怎么做出来的,如果是用electron
该怎么实现呢?
官方示例
老规矩,上
electron
官方文档,看有没有支持的Api
官方文档还是比较简单的,支持icon, title, 阐述了兼容性。
那我们就拿官方的示例,看看效果。
let tray1 = null;
app.whenReady().then(() => {
const path = require("path");
tray1 = new Tray(path.resolve("./lamian.png"));
const contextMenu = Menu.buildFromTemplate([
{ label: "Item1", type: "radio" },
{ label: "Item2", type: "radio" },
{ label: "Item3", type: "radio", checked: true },
{ label: "Item4", type: "radio" }
]);
tray1.setToolTip("This is my application.");
tray1.setContextMenu(contextMenu);
});
复制代码
果然是官方
,够简单
探
那支不支持,自定义元素呢?
官方Menu已经说了,label只支持string, 看来是没有办法实现这么一个自定义的弹窗了。
等等,弹窗
?
那可不可以点击托盘,打开一个BrowserWindow
, 然后将弹窗位置定位到托盘下方!!
初步成果
自定义弹窗
const toggleVisible = () => {
const isVisible = win.isVisible();
isVisible ? existWin.hide() : existWin.show();
};
app.whenReady().then(async () => {
const win = new BrowserWindow({
show: false,
fullscreen: false,
alwaysOnTop: true,
transparent: true,
frame: false,
resizable: false,
width: 300,
hight: 600
});
win.onBlur(() => {
win.hide();
});
const path = require("path");
const paths = path.resolve("./lamian.png")
tray = new Tray(paths);
tray.on("click", toggleVisible);
tray.on("double-click", toggleVisible);
const trayBounds = tray.getBounds();
const windowBounds = win.getBounds();
const x = Math.round(
trayBounds.x - trayBounds.width / 2 - windowBounds.width / 2
);
const y = Math.round(trayBounds.y + trayBounds.height + 3);
win.setPosition(x, y, true);
win.show();
});
复制代码
这样弹窗的元素就可以想怎么写就怎么写了
自定义托盘标题
那像如上的带颜色的托盘标题怎么实现的呢?
官方回复
tray.setTitle(title, { fontType: '...' })
title只支持string,
Sets the title displayed next to the tray icon in the status bar (Support ANSI colors).
复制代码
Support ANSI colors
, ANSI colors是什么?
ANSI colors,可以查看此文,我们可以用ANSI编码格式去设置颜色,例如:
"\u001b[31m我是红色文字\u001b[39m"
大家可以在浏览器控制台输入:
console.log("\u001b[31m我是红色文字\u001b[39m")
复制代码
如此就可以设置标题的颜色了
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END