const { app, BrowserWindow, Tray, Menu } = require('electron') const path = require('path') console.log('=== 退出功能测试 ===') let mainWindow = null let tray = null // 单实例检查 const gotTheLock = app.requestSingleInstanceLock() if (!gotTheLock) { console.log('❌ 检测到已有实例运行,退出当前实例') app.quit() } else { console.log('✅ 这是第一个实例,继续启动') // 监听第二个实例 app.on('second-instance', (event, commandLine, workingDirectory) => { console.log('检测到第二个实例启动,激活现有实例') if (mainWindow) { if (mainWindow.isMinimized()) { mainWindow.restore() } mainWindow.show() mainWindow.focus() } }) // 创建窗口 function createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, contextIsolation: false } }) mainWindow.loadURL('data:text/html,

退出功能测试

PID: ' + process.pid + '

时间: ' + new Date().toLocaleString() + '

点击托盘图标右键菜单中的"退出应用"来测试退出功能

') console.log('窗口已创建,PID:', process.pid) mainWindow.on('closed', () => { mainWindow = null }) } // 创建托盘 function createTray() { tray = new Tray(path.join(__dirname, 'resources', 'icon.png')) const contextMenu = Menu.buildFromTemplate([ { label: '显示窗口', click: () => { if (mainWindow) { mainWindow.show() } } }, { label: '隐藏窗口', click: () => { if (mainWindow) { mainWindow.hide() } } }, { type: 'separator' }, { label: '退出应用', click: () => { console.log('用户点击退出应用') // 确保所有窗口都被关闭 const windows = require('electron').BrowserWindow.getAllWindows() console.log(`准备关闭 ${windows.length} 个窗口`) windows.forEach(window => { if (!window.isDestroyed()) { try { window.destroy() console.log('窗口销毁成功') } catch (error) { console.log('销毁窗口时出错:', error) } } }) // 延迟执行退出,确保窗口销毁完成 setTimeout(() => { try { console.log('执行应用退出') // 使用 exit 而不是 quit,确保完全退出 app.exit(0) } catch (error) { console.log('应用退出失败,尝试强制退出:', error) try { process.exit(0) } catch (processError) { console.log('强制退出也失败:', processError) // 最后的强制退出 process.kill(process.pid, 'SIGKILL') } } }, 500) } } ]) tray.setContextMenu(contextMenu) tray.setToolTip('退出功能测试') // 点击托盘图标 tray.on('click', () => { if (mainWindow) { if (mainWindow.isVisible()) { mainWindow.hide() } else { mainWindow.show() } } }) } app.whenReady().then(() => { console.log('应用已准备就绪') createWindow() createTray() }) app.on('window-all-closed', () => { console.log('所有窗口已关闭') if (process.platform !== 'darwin') { app.quit() } }) app.on('before-quit', () => { console.log('应用即将退出') }) app.on('will-quit', () => { console.log('应用即将退出') }) app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }