基于 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)
import { Tray, Menu, BrowserWindow, nativeImage, app } from 'electron'
import path from 'path'let tray: Tray | null = nullexport 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)
mainWindow.on('close', (e) => {if (!app.isQuiting) {e.preventDefault()mainWindow.hide()}
})
?? 3. 開機啟動功能(electron/main/autostart.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)
import { enableAutoLaunch } from './autostart'
import { createTray } from './tray'app.whenReady().then(() => {mainWindow = createWindow()enableAutoLaunch()createTray(mainWindow)
})
🧪 注意事項(平臺兼容)
功能 | Windows | macOS | Linux |
---|---|---|---|
托盤 | ? 完全支持 | ? 支持(建議使用 Template 圖標) | ?? 依賴桌面環境 |
開機自啟 | ? | ?(需簽名或添加權限) | ?? 建議用 auto-launch |
? 效果總結
功能項 | 效果說明 |
---|---|
托盤交互 | 支持點擊/雙擊托盤控制窗口 |
窗口關閉 | 不退出程序,僅隱藏 |
托盤菜單 | 顯示主界面 / 退出程序 |
開機自啟 | 系統啟動時自動運行 Electron 應用 |
📚 推薦閱讀
- Electron 官方 Tray 文檔
- Electron 開機啟動說明
- electron-vite-vue 模板