[Electron] 应用不关闭窗口退出而是保留到后台运行
macOS
不是关闭窗口退出应用,而是关闭窗口保留应用为后台进程。Windows
等系统默认关闭窗口就是退出应用也不保留后台进程。若要让 Windows
也可以实现该行为,在 electron
中可以添加如下代码实现:
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();
});
});
// 被禁止默认关闭行为,所以这下面代码可要可不要
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});