[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();
}
});
分类:
软件开发 / Web 前端
标签:
Electron
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2023-10-05 [Spring MVC] Get 请求获取参数可以不使用 @RequestParam,通过实体类封装并获取