
介绍
electron js 是一种流行的框架,用于使用 javascript、html 和 css 等 web 技术构建桌面应用程序。桌面应用程序的重要功能之一是能够将它们与系统托盘集成,从而允许用户轻松访问关键功能和设置。本文将指导您创建一个 electron js 应用程序并将其与系统托盘集成。
在系统托盘中显示应用程序
要在系统托盘中显示您的应用程序,您需要从 electron 创建 tray 类的实例。此实例将在系统托盘中用图标代表该应用程序。
将以下行添加到 main.js 文件中:
const { app, browserwindow, tray, menu } = require('electron');
let mainwindow;
let tray;
app.on('ready', () => {
mainwindow = new browserwindow({
width: 800,
height: 600,
webpreferences: {
nodeintegration: true
}
});
mainwindow.loadfile('index.html');
createtray();
});
function createtray() {
tray = new tray('path/to/icon.png'); // path to your tray icon
const contextmenu = menu.buildfromtemplate([
{
label: 'show app',
click: () => {
mainwindow.show();
}
}
]);
tray.settooltip('my electron app');
tray.setcontextmenu(contextmenu);
}
自定义图标
要更改托盘图标,请更新托盘构造函数中的路径:
tray = new tray('path/to/new_icon.png');
确保路径指向要用作托盘图标的有效图像文件。
添加显示、隐藏和退出按钮
为了增强系统托盘菜单的功能,您可以添加显示、隐藏和退出应用程序的选项。修改main.js文件如下:
一套面向小企业用户的企业网站程序!功能简单,操作简单。实现了小企业网站的很多实用的功能,如文章新闻模块、图片展示、产品列表以及小型的下载功能,还同时增加了邮件订阅等相应模块。公告,友情链接等这些通用功能本程序也同样都集成了!同时本程序引入了模块功能,只要在系统默认模板上创建模块,可以在任何一个语言环境(或任意风格)的适当位置进行使用!
const { app, browserwindow, tray, menu } = require('electron');
let mainwindow;
let tray;
app.on('ready', () => {
mainwindow = new browserwindow({
width: 800,
height: 600,
webpreferences: {
nodeintegration: true
}
});
mainwindow.loadfile('index.html');
createtray();
});
function createtray() {
tray = new tray('path/to/icon.png'); // path to your tray icon
const contextmenu = menu.buildfromtemplate([
{
label: 'show app',
click: () => {
mainwindow.show();
}
},
{
label: 'hide app',
click: () => {
mainwindow.hide();
}
},
{
label: 'exit',
click: () => {
app.quit();
}
}
]);
tray.settooltip('my electron app');
tray.setcontextmenu(contextmenu);
}
解释
- 显示应用程序按钮:
{
label: 'show app',
click: () => {
mainwindow.show();
}
}
单击此菜单项将使应用程序的窗口重新显示出来。
- 隐藏应用程序按钮:
{
label: 'hide app',
click: () => {
mainwindow.hide();
}
}
此菜单项会将应用程序最小化到系统托盘,将其从任务栏隐藏。
- 退出按钮:
{
label: 'exit',
click: () => {
app.quit();
}
}
选择此菜单项将关闭应用程序。
完整的上下文菜单示例
您可以通过添加更多选项来进一步自定义上下文菜单,例如打开设置窗口或显示应用程序信息。
const { app, BrowserWindow, Tray, Menu } = require('electron');
let mainWindow;
let tray;
app.on('ready', () => {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadFile('index.html');
createTray();
});
function createTray() {
tray = new Tray('path/to/icon.png'); // Path to your tray icon
const contextMenu = Menu.buildFromTemplate([
{
label: 'Show App',
click: () => {
mainWindow.show();
}
},
{
label: 'Hide App',
click: () => {
mainWindow.hide();
}
},
{
label: 'Settings',
click: () => {
// Open a settings window
}
},
{
label: 'About',
click: () => {
// Show about information
}
},
{
label: 'Exit',
click: () => {
app.quit();
}
}
]);
tray.setToolTip('My Electron App');
tray.setContextMenu(contextMenu);
}
结论
按照以下步骤,您可以使用 electron js 创建一个与系统托盘无缝集成的桌面应用程序。这种集成通过直接从系统托盘轻松访问基本应用程序功能来增强用户体验。无论是显示、隐藏还是退出应用程序,系统托盘都为用户与您的应用程序交互提供了便捷的方式。









