增加系统托盘

This commit is contained in:
刘嘉伟 2023-12-01 15:00:11 +08:00
parent c9acbfc5f5
commit b957414e48

View File

@ -1,6 +1,6 @@
import { app, BrowserWindow, ipcMain, shell } from "electron";
import {app, BrowserWindow, ipcMain, Menu, MenuItem, MenuItemConstructorOptions, shell, Tray} from "electron";
import {release} from "node:os";
import { join } from "node:path";
import node_path, {join} from "node:path";
import {initGitHubApi} from "../api/github";
import {initConfigApi} from "../api/config";
import {initProxyApi} from "../api/proxy";
@ -40,15 +40,17 @@ if (!app.requestSingleInstanceLock()) {
// process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
let win: BrowserWindow | null = null;
let tray = null;
// Here, you can also use other preload
const preload = join(__dirname, "../preload/index.js");
const url = process.env.VITE_DEV_SERVER_URL;
const indexHtml = join(process.env.DIST, "index.html");
let isQuiting;
async function createWindow() {
win = new BrowserWindow({
title: "Main window",
icon: join(process.env.VITE_PUBLIC, "favicon.ico"),
title: "Frpc Desktop",
icon: join(process.env.VITE_PUBLIC, "logo/16x16.png"),
webPreferences: {
preload,
// Warning: Enable nodeIntegration and disable contextIsolation is not secure in production
@ -58,7 +60,6 @@ async function createWindow() {
contextIsolation: false
}
});
if (process.env.VITE_DEV_SERVER_URL) {
// electron-vite-vue#298
win.loadURL(url);
@ -86,10 +87,54 @@ async function createWindow() {
if (process.platform !== "darwin") {
app.dock.hide();
}
// win.webContents.on('will-navigate', (event, url) => { }) #344
win.on('minimize', function (event) {
event.preventDefault();
win.hide();
});
win.on('close', function (event) {
if (!isQuiting) {
event.preventDefault();
win.hide();
if (process.platform === "darwin") {
app.dock.hide();
}
}
return false;
});
}
app.whenReady().then(createWindow);
export const createTray = () => {
let menu: Array<(MenuItemConstructorOptions) | (MenuItem)> = [
{
label: '显示主窗口', click: function () {
win.show();
if (process.platform === "darwin") {
app.dock.show();
}
}
},
{
label: '退出',
click: () => {
isQuiting = true;
app.quit();
}
}
];
tray = new Tray(node_path.join(process.env.VITE_PUBLIC, "logo/16x16.png"))
tray.setToolTip('Frpc Desktop')
const contextMenu = Menu.buildFromTemplate(menu)
tray.setContextMenu(contextMenu)
}
app.whenReady().then(() => {
createWindow().then(r => {
createTray()
})
});
app.on("window-all-closed", () => {
win = null;
@ -113,6 +158,10 @@ app.on("activate", () => {
}
});
app.on('before-quit', () => {
isQuiting = true;
})
// New window example arg: new windows url
ipcMain.handle("open-win", (_, arg) => {
const childWindow = new BrowserWindow({
@ -131,7 +180,8 @@ ipcMain.handle("open-win", (_, arg) => {
});
ipcMain.on('open-url', (event, url) => {
shell.openExternal(url).then(r => {});
shell.openExternal(url).then(r => {
});
});
initGitHubApi();