const { app, BrowserWindow, Tray, Menu, nativeImage, ipcMain } = require('electron'); const path = require('path'); const AutoLaunch = require('auto-launch'); // 保持对窗口对象的全局引用,如果不这样做,窗口将会在JavaScript垃圾回收时自动关闭 let mainWindow; let tray = null; // 创建开机启动管理器 let autoLauncher = new AutoLaunch({ name: 'Motioner', path: process.execPath, }); // 创建窗口的函数 function createWindow() { // 创建浏览器窗口 mainWindow = new BrowserWindow({ width: 300, height: 200, webPreferences: { nodeIntegration: true, contextIsolation: false }, // 创建无边框窗口 frame: false, // 保持窗口始终在最前面 alwaysOnTop: true, // 窗口透明 transparent: true }); // 加载应用的index.html mainWindow.loadFile('index.html'); // 处理最小化事件 ipcMain.on('window-minimize', () => { mainWindow.hide(); }); // 处理关闭事件 ipcMain.on('window-close', () => { app.quit(); }); // 处理开机启动设置事件 ipcMain.on('set-auto-launch', (event, enable) => { if (enable) { autoLauncher.enable().then(() => { console.log('开机启动已启用'); }).catch(err => { console.error('启用开机启动失败:', err); }); } else { autoLauncher.disable().then(() => { console.log('开机启动已禁用'); }).catch(err => { console.error('禁用开机启动失败:', err); }); } }); // 当窗口关闭时触发 mainWindow.on('closed', function () { // 取消对窗口对象的引用,通常会存储窗口在数组中,这是删除相应元素的时候 mainWindow = null; }); } // 当Electron完成初始化并准备创建浏览器窗口时调用此方法 app.whenReady().then(() => { createWindow(); // 创建系统托盘 createTray(); app.on('activate', function () { // 在macOS上,当单击dock图标并且没有其他窗口打开时,通常在应用程序中重新创建一个窗口 if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); }); // 当所有窗口都关闭时退出应用 app.on('window-all-closed', function () { // 在macOS上,应用程序及其菜单栏通常会保持活动状态,直到用户明确退出 if (process.platform !== 'darwin') app.quit(); }); // 创建系统托盘 function createTray() { // 创建托盘图标 const iconPath = path.join(__dirname, 'assets/icon.png'); let icon; try { icon = nativeImage.createFromPath(iconPath); } catch (error) { // 如果找不到图标文件,使用默认图标 icon = nativeImage.createEmpty(); } tray = new Tray(icon); // 创建上下文菜单 const contextMenu = Menu.buildFromTemplate([ { label: '显示', click: () => { mainWindow.show(); } }, { label: '退出', click: () => { app.quit(); } } ]); tray.setContextMenu(contextMenu); // 点击托盘图标显示窗口 tray.on('click', () => { mainWindow.show(); }); }