| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- import type {BrowserWindowConstructorOptions} from 'electron';
- import {app, BrowserWindow, dialog} from 'electron';
- import path from 'path';
- import {_PATHS} from '../paths';
- import {$env, isDev} from '../env';
- import {createTray} from './tray';
- // 获取公共窗口选项
- export function getBrowserWindowOptions(options?: BrowserWindowConstructorOptions): BrowserWindowConstructorOptions {
- return {
- width: 1200,
- height: 800,
- webPreferences: {
- preload: path.join(_PATHS.preloadRoot, 'index.js'),
- nodeIntegration: false,
- contextIsolation: true,
- },
- // 应用图标
- icon: isDev ? _PATHS.appIcon : void 0,
- ...options,
- }
- }
- // 创建窗口
- export function createBrowserWindow(options?: BrowserWindowConstructorOptions) {
- const win = new BrowserWindow(getBrowserWindowOptions(options));
- // 代码逻辑说明: 【JHHB-13】桌面应用消息通知
- if (process.platform === 'darwin') { // 仅 macOS 生效
- if (app.dock) {
- app.dock.setIcon(path.join(_PATHS.electronRoot, './icons/mac/dock.png').replace(/[\\/]dist[\\/]/, '/'));
- }
- }
- // 设置窗口打开处理器
- win.webContents.setWindowOpenHandler(() => {
- return {
- action: 'allow',
- // 覆写新窗口的选项,用于调整默认尺寸和加载preload脚本等
- overrideBrowserWindowOptions: getBrowserWindowOptions(),
- }
- });
- // 当 beforeunload 阻止窗口关闭时触发
- win.webContents.on('will-prevent-unload', () => {
- const choice = dialog.showMessageBoxSync(win, {
- type: 'question',
- title: '确认关闭吗?',
- message: '系统可能不会保存您所做的更改。',
- buttons: ['关闭', '取消'],
- defaultId: 1,
- cancelId: 1,
- noLink: true,
- });
- // 用户选择了关闭,直接销毁窗口
- if (choice === 0) {
- win.destroy();
- }
- });
- return win;
- }
- // 创建主窗口、系统托盘
- export function createMainWindow() {
- const win = createIndexWindow()
- // 设置系统托盘图标
- createTray(win);
- // 主窗口尝试关闭时,默认不直接退出应用,而是隐藏到托盘
- win.on('close', (event) => {
- event.preventDefault();
- win.hide();
- });
- return win;
- }
- // 创建索引窗口
- export function createIndexWindow() {
- const win = createBrowserWindow({
- width: 1600,
- height: 1000,
- title: $env.VITE_GLOB_APP_TITLE!,
- });
- // 开发环境加载Vite服务,生产加载打包文件
- if (isDev) {
- let serverUrl = $env.VITE_DEV_SERVER_URL! as string;
- // 【JHHB-936】由于wps预览不能使用localhost访问,所以把localhost替换为127.0.0.1
- serverUrl = serverUrl.replace('localhost', '127.0.0.1');
- win.loadURL(serverUrl)
- // 开发环境下,自动打开调试工具
- // win.webContents.openDevTools()
- } else {
- win.loadFile(path.join(_PATHS.publicRoot, 'index.html'));
- }
- return win;
- }
|