[Electron] 應用不關閉視窗退出而是保留到後臺執行

Himmelbleu發表於2024-10-05
import { app, BrowserWindow, Tray, Menu } from "electron";
import { fileURLToPath } from "url";
import path from "path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let tray = null;

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600
  });

  win.loadURL("http://localhost:5173");

  win.webContents.openDevTools();

  win.on("close", (e) => {
    e.preventDefault(); // 阻止退出程式
    win.setSkipTaskbar(true); // 取消工作列顯示
    win.hide(); // 隱藏主程式視窗
  });

  tray = new Tray(path.join(__dirname, "icons", "favicon.ico"));

  const contextMenu = Menu.buildFromTemplate([
    {
      label: "退出",
      click: function () {
        win.destroy();
        app.quit();
      }
    }
  ]);

  tray.setToolTip("Vite+Vue3+Electron");
  tray.setContextMenu(contextMenu);
  tray.on("click", () => {
    win.show();
  });
};

app.whenReady().then(() => {
  createWindow();

  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

相關文章