main.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // 使用 CommonJS 格式
  2. const { app, BrowserWindow, ipcMain, shell } = require('electron');
  3. const { join } = require('path');
  4. let mainWindow: typeof BrowserWindow.prototype | null = null;
  5. const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL;
  6. function createWindow() {
  7. mainWindow = new BrowserWindow({
  8. width: 1400,
  9. height: 900,
  10. minWidth: 1200,
  11. minHeight: 700,
  12. webPreferences: {
  13. preload: join(__dirname, 'preload.js'),
  14. nodeIntegration: false,
  15. contextIsolation: true,
  16. },
  17. titleBarStyle: 'hiddenInset',
  18. frame: process.platform !== 'darwin',
  19. show: false,
  20. });
  21. // 窗口准备好后再显示,避免白屏
  22. mainWindow.once('ready-to-show', () => {
  23. mainWindow?.show();
  24. });
  25. // 加载页面
  26. if (VITE_DEV_SERVER_URL) {
  27. mainWindow.loadURL(VITE_DEV_SERVER_URL);
  28. mainWindow.webContents.openDevTools();
  29. } else {
  30. mainWindow.loadFile(join(__dirname, '../dist/index.html'));
  31. }
  32. // 处理外部链接
  33. mainWindow.webContents.setWindowOpenHandler(({ url }: { url: string }) => {
  34. shell.openExternal(url);
  35. return { action: 'deny' };
  36. });
  37. mainWindow.on('closed', () => {
  38. mainWindow = null;
  39. });
  40. }
  41. // 单实例锁定
  42. const gotTheLock = app.requestSingleInstanceLock();
  43. if (!gotTheLock) {
  44. app.quit();
  45. } else {
  46. app.on('second-instance', () => {
  47. if (mainWindow) {
  48. if (mainWindow.isMinimized()) mainWindow.restore();
  49. mainWindow.focus();
  50. }
  51. });
  52. app.whenReady().then(() => {
  53. createWindow();
  54. app.on('activate', () => {
  55. if (BrowserWindow.getAllWindows().length === 0) {
  56. createWindow();
  57. }
  58. });
  59. });
  60. }
  61. app.on('window-all-closed', () => {
  62. if (process.platform !== 'darwin') {
  63. app.quit();
  64. }
  65. });
  66. // IPC 处理
  67. ipcMain.handle('get-app-version', () => {
  68. return app.getVersion();
  69. });
  70. ipcMain.handle('get-platform', () => {
  71. return process.platform;
  72. });
  73. // 窗口控制
  74. ipcMain.on('window-minimize', () => {
  75. mainWindow?.minimize();
  76. });
  77. ipcMain.on('window-maximize', () => {
  78. if (mainWindow?.isMaximized()) {
  79. mainWindow.unmaximize();
  80. } else {
  81. mainWindow?.maximize();
  82. }
  83. });
  84. ipcMain.on('window-close', () => {
  85. mainWindow?.close();
  86. });