import{ app, shell, BrowserWindow, ipcMain }from'electron'import{ join }from'path'import{ electronApp, optimizer, is }from'@electron-toolkit/utils'import icon from'../../resources/icon.png?asset'/**
* @description 创建主窗口
* 1、通过 new BrowserWindow 创建窗口,并设置了窗口的一系列属性,比如宽度、高度、是否显示、是否隐藏菜单栏等
* 2、通过 on('ready-to-show', () => { mainWindow.show() }) 在窗口准备好显示时显示窗口
* 3、通过 webContents.setWindowOpenHandler((details) => { shell.openExternal(details.url) }) 设置窗口打开链接的行为
* 4、通过 loadURL(process.env['ELECTRON_RENDERER_URL']) 加载渲染进程的 URL,如果是在开发环境下,则加载 process.env['ELECTRON_RENDERER_URL'],否则加载本地的 index.html 文件
*/functioncreateWindow(){// Create the browser window.const mainWindow =newBrowserWindow({width:900,height:670,show:false,autoHideMenuBar:true,...(process.platform ==='linux'?{ icon }:{}),webPreferences:{preload:join(__dirname,'../preload/index.js'),sandbox:false}})
mainWindow.on('ready-to-show',()=>{
mainWindow.show()})
mainWindow.webContents.setWindowOpenHandler((details)=>{
shell.openExternal(details.url)return{action:'deny'}})// HMR for renderer base on electron-vite cli.// Load the remote URL for development or the local html file for production.if(is.dev && process.env['ELECTRON_RENDERER_URL']){
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])}else{
mainWindow.loadFile(join(__dirname,'../renderer/index.html'))}}/**
* @description 当 Electron 完成初始化并且准备好创建浏览器窗口时,这个方法会被调用
* 1、通过 electronApp.setAppUserModelId('com.electron') 设置应用的用户模型 ID
* 2、通过 app.on('browser-window-created', (_, window) => { optimizer.watchWindowShortcuts(window) }) 监听浏览器窗口创建事件,并使用 optimizer.watchWindowShortcuts(window) 监听窗口快捷键
* 3、通过 ipcMain.on('ping', () => console.log('pong')) 监听渲染进程发送的 ping 事件,并返回 pong
* 4、通过 createWindow() 创建主窗口
* 5、通过 app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) 监听激活事件,如果没有任何窗口打开,则创建一个新窗口
*/
app.whenReady().then(()=>{// Set app user model id for windows
electronApp.setAppUserModelId('com.electron')// Default open or close DevTools by F12 in development// and ignore CommandOrControl + R in production.// see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
app.on('browser-window-created',(_, window)=>{
optimizer.watchWindowShortcuts(window)})// 监听渲染进程发送的 ping 事件,并返回 pong
ipcMain.on('ping',()=> console.log('pong'))createWindow()
app.on('activate',function(){// On macOS it's common to re-create a window in the app when the// dock icon is clicked and there are no other windows open.if(BrowserWindow.getAllWindows().length ===0)createWindow()})})/**
* @description 当所有窗口关闭时,如果是在 macOS 上,则不退出应用程序,否则退出应用程序
*/
app.on('window-all-closed',()=>{if(process.platform !=='darwin'){
app.quit()}})// In this file you can include the rest of your app's specific main process// code. You can also put them in separate files and require them here.