From 08974f03526fc57aa2ffb84333d53e2bf340e090 Mon Sep 17 00:00:00 2001 From: zlm Date: Wed, 10 Jun 2026 14:41:18 +0800 Subject: [PATCH] fix: 16x16 icon, start/stop buttons with state --- desktop/src/main.js | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/desktop/src/main.js b/desktop/src/main.js index c1e3a5b..376373c 100644 --- a/desktop/src/main.js +++ b/desktop/src/main.js @@ -1,17 +1,33 @@ const { app, Tray, Menu, nativeImage } = require('electron') -const { spawn } = require('child_process') +const { spawn, exec } = require('child_process') const path = require('path') const PROJECT_DIR = path.resolve(__dirname, '../../project') let backend = null let tray = null +let isRunning = false const ICON = nativeImage.createFromBuffer(Buffer.from( 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVR4nO3OIQEAAAgDMHJg6Ul1iHEzMb/q2UsqAQEBAQEBAQEBAQEBAQGBdOABvyXoW2Q1L3wAAAAASUVORK5CYII=', 'base64' )) +function updateMenu() { + tray.setContextMenu(Menu.buildFromTemplate([ + { label: '打开页面', click: () => exec('start http://localhost:3000') }, + { type: 'separator' }, + { label: '启动服务', enabled: !isRunning, click: startBackend }, + { label: '停止服务', enabled: isRunning, click: stopBackend }, + { type: 'separator' }, + { label: '退出', click: () => { stopBackend(); app.quit() } }, + ])) +} + function startBackend() { + if (backend) return + isRunning = true + updateMenu() + backend = spawn('npm.cmd', ['run', 'start'], { cwd: PROJECT_DIR, stdio: 'ignore', @@ -19,22 +35,26 @@ function startBackend() { shell: true, windowsHide: true, }) - backend.on('exit', () => { backend = null }) + + backend.on('exit', () => { + backend = null + isRunning = false + updateMenu() + }) } function stopBackend() { - if (backend) { backend.kill('SIGTERM'); backend = null } + if (!backend) return + isRunning = false + updateMenu() + backend.kill('SIGTERM') + backend = null } app.whenReady().then(() => { - tray = new Tray(ICON.resize({ width: 32, height: 32 })) + tray = new Tray(ICON.resize({ width: 16, height: 16 })) tray.setToolTip('质量追溯系统') - tray.setContextMenu(Menu.buildFromTemplate([ - { label: '打开页面', click: () => require('child_process').exec('start http://localhost:3000') }, - { type: 'separator' }, - { label: '退出', click: () => { stopBackend(); app.quit() } }, - ])) - + updateMenu() startBackend() })