electron托盘图标左键和右键点击的时候,可以执行相应的操作
//托盘图标左键点击事件
tray.on('click',(event)=>{
//执行相应的操作
});
//托盘图标右键点击事件
tray.on('right-click',(event)=>{
//执行相应的操作
});
tray.on('click',(event)=>{
//执行相应的操作
});
//托盘图标右键点击事件
tray.on('right-click',(event)=>{
//执行相应的操作
});
下面以左键点击显示窗口,右键点击显示右键菜单为例:
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/icon3.png');
//生成上下文菜单
contextMenu = Menu.buildFromTemplate([
{label:'复制',role:'copy'},
{label:'粘贴',role:'paste'},
{label:'剪切',role:'cut'}
]);
tray.setToolTip('托盘图标提示文本');//鼠标移到托盘图标上会提示这段文本
//托盘图标左键点击事件
tray.on('click',(event)=>{
win.show();
});
//托盘图标右键点击事件
tray.on('right-click',(event)=>{
tray.popUpContextMenu(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/icon3.png');
//生成上下文菜单
contextMenu = Menu.buildFromTemplate([
{label:'复制',role:'copy'},
{label:'粘贴',role:'paste'},
{label:'剪切',role:'cut'}
]);
tray.setToolTip('托盘图标提示文本');//鼠标移到托盘图标上会提示这段文本
//托盘图标左键点击事件
tray.on('click',(event)=>{
win.show();
});
//托盘图标右键点击事件
tray.on('right-click',(event)=>{
tray.popUpContextMenu(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();
}
});