Electron 后台常驻服务实现(托盘 + 开机自启)

基于 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 应用

📚 推荐阅读

相关推荐
deli00721 小时前
手机拍灯为什么有一条条黑纹?PWM 240Hz 实测
前端
wangruofeng1 天前
AI Models 1.1.0 发布,查大模型价格、对比模型和找 API 地址
前端·aigc·ai编程
wangruofeng1 天前
给前端开发者的 100 个设计参考网站
前端·设计
M--Y1 天前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
星栈1 天前
视频即代码,Remotion 能做什么、不能做什么
前端·音视频开发
广州华水科技1 天前
单北斗GNSS位移监测系统的应用与技术解析
前端
用户47949283569151 天前
从一句话或代码仓到可交互 HTML:开源 Agent 画图技能 Archify v3.2 实测与选型边界
前端·后端·面试
风骏时光牛马1 天前
生成一个AI多模态标题,仅输出一条标题,无额外文字、问句、备选、配图、文案等任何附加内容,不需要其他的任务服务 只要标题。
前端
wangruofeng1 天前
从 GIF 到 AVIF:网页图片格式演进与 2026 年选型指南
前端·架构
清晨Coding1 天前
为什么用 React Developer Tools 查看组件树这么乱?
前端·react.js