基于 electron-vite-vue 项目结构
本篇将详细介绍如何为 Electron 应用实现后台常驻运行,包括:
- ✅ 创建系统托盘图标(Tray)
- ✅ 支持点击托盘菜单控制窗口显示/退出
- ✅ 实现开机自启功能(Auto Launch)
📁 项目结构建议
electron-vite-vue/
├── electron/
│ ├── main/
│ │ ├── index.ts # 主进程入口
│ │ ├── tray.ts # 托盘功能实现
│ │ └── autostart.ts # 开机启动功能
├── resources/
│ └── iconTemplate.png # 托盘图标
├── src/
│ └── App.vue
└── package.json
🖼️ 1. 托盘功能实现(electron/main/tray.ts)
ts
import { Tray, Menu, BrowserWindow, nativeImage, app } from 'electron'
import path from 'path'
let tray: Tray | null = null
export function createTray(win: BrowserWindow) {
const icon = nativeImage.createFromPath(
path.join(__dirname, '../../resources/iconTemplate.png')
)
icon.setTemplateImage(true) // macOS 支持暗黑模式适配
tray = new Tray(icon)
tray.setToolTip('我的 Electron 应用')
const contextMenu = Menu.buildFromTemplate([
{ label: '显示窗口', click: () => win.show() },
{ label: '退出', click: () => { app.quit() } }
])
tray.setContextMenu(contextMenu)
tray.on('click', () => {
win.isVisible() ? win.hide() : win.show()
})
tray.on('double-click', () => {
win.show()
})
}
🧩 2. 主窗口关闭时隐藏到托盘(electron/main/index.ts)
ts
mainWindow.on('close', (e) => {
if (!app.isQuiting) {
e.preventDefault()
mainWindow.hide()
}
})
⚙️ 3. 开机启动功能(electron/main/autostart.ts)
ts
import { app } from 'electron'
export function enableAutoLaunch() {
app.setLoginItemSettings({
openAtLogin: true,
path: app.getPath('exe') // 自动获取应用路径
})
}
Windows/macOS 默认支持。Linux 需要创建
.desktop
文件或使用auto-launch
库。
🔗 4. 在主进程入口中调用(electron/main/index.ts)
ts
import { enableAutoLaunch } from './autostart'
import { createTray } from './tray'
app.whenReady().then(() => {
mainWindow = createWindow()
enableAutoLaunch()
createTray(mainWindow)
})
🧪 注意事项(平台兼容)
功能 | Windows | macOS | Linux |
---|---|---|---|
托盘 | ✅ 完全支持 | ✅ 支持(建议使用 Template 图标) | ⚠️ 依赖桌面环境 |
开机自启 | ✅ | ✅(需签名或添加权限) | ⚠️ 建议用 auto-launch |
✅ 效果总结
功能项 | 效果说明 |
---|---|
托盘交互 | 支持点击/双击托盘控制窗口 |
窗口关闭 | 不退出程序,仅隐藏 |
托盘菜单 | 显示主界面 / 退出程序 |
开机自启 | 系统启动时自动运行 Electron 应用 |