electron添加托盘图标需要引入Tray模块,只需要new Tray()就可以创建一个托盘图标,参数是图标的路径。
tray = new Tray(image);
给托盘图标设置提示文本
.setToolTip('托盘图标提示文本');
给托盘图标设置上下文菜单
tray.setContextMenu(contextMenu);
例子如下:
const {app,BrowserWindow,Menu,Tray} = require('electron');
let tray;
let contextMenu;
function createWindow(){
win = new BrowserWindow({
show:false,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
//添加托盘图标
tray = new Tray('./images/icon.png');
//生成上下文菜单
contextMenu = Menu.buildFromTemplate([
{label:'复制',role:'copy'},
{label:'粘贴',role:'paste'},
{label:'剪切',role:'cut'}
]);
tray.setToolTip('托盘图标提示文本');//鼠标移到托盘图标上会提示这段文本
tray.setContextMenu(contextMenu);//为托盘图标添加上下文菜单
win.on('ready-to-show',()=>{
win.show();
});
win.on('closed',()=>{
console.log('closed');
win = null;
});
//打开开发者工具
win.webContents.openDevTools();
}
app.allowRendererProcessReuse = true;
app.on('ready',createWindow);
app.on('window-all-closed',()=>{
console.log('window-all-closed');
if(process.platform != 'darwin'){
app.quit();
}
});
app.on('activate',()=>{
console.log('activate');
if(win == null) {
createWindow();
}
});
let tray;
let contextMenu;
function createWindow(){
win = new BrowserWindow({
show:false,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
//添加托盘图标
tray = new Tray('./images/icon.png');
//生成上下文菜单
contextMenu = Menu.buildFromTemplate([
{label:'复制',role:'copy'},
{label:'粘贴',role:'paste'},
{label:'剪切',role:'cut'}
]);
tray.setToolTip('托盘图标提示文本');//鼠标移到托盘图标上会提示这段文本
tray.setContextMenu(contextMenu);//为托盘图标添加上下文菜单
win.on('ready-to-show',()=>{
win.show();
});
win.on('closed',()=>{
console.log('closed');
win = null;
});
//打开开发者工具
win.webContents.openDevTools();
}
app.allowRendererProcessReuse = true;
app.on('ready',createWindow);
app.on('window-all-closed',()=>{
console.log('window-all-closed');
if(process.platform != 'darwin'){
app.quit();
}
});
app.on('activate',()=>{
console.log('activate');
if(win == null) {
createWindow();
}
});