这篇笔记我们简单介绍Electron框架中和系统相关的功能,由于这些功能和操作系统紧密相关,因此这里仅以Windows为例进行介绍。
Windows的托盘一般位于右下角,下面代码我们为程序添加了一个托盘图标,并为其添加了一个菜单,点击菜单中的Exit
选项时将退出程序。
const { app, BrowserWindow, Tray, Menu, nativeImage } = require('electron');
const path = require('path');
const createWindow = () => {
// 创建窗口
const window = new BrowserWindow({
width: 800,
height: 600
});
// 加载HTML文件
window.loadFile('index.html');
};
app.whenReady().then(() => {
const trayIcon = nativeImage.createFromPath(path.join(__dirname, 'assets/icon.png'));
const tray = new Tray(trayIcon);
const trayMenu = Menu.buildFromTemplate([
{label: 'Exit', click: () => {app.quit()}}
]);
tray.setContextMenu(trayMenu);
tray.setTitle('my title');
tray.setToolTip('my tooltip');
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
})
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});