electron-vite-react/src/main/index.ts

65 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-12-09 09:18:00 +08:00
import os from 'os'
2021-11-08 19:17:39 +08:00
import { join } from 'path'
import { app, BrowserWindow } from 'electron'
import './samples/electron-store'
2021-11-08 19:17:39 +08:00
2021-12-09 09:18:00 +08:00
const isWin7 = os.release().startsWith('6.1')
if (isWin7) app.disableHardwareAcceleration()
2021-11-09 11:12:32 +08:00
if (!app.requestSingleInstanceLock()) {
app.quit()
process.exit(0)
}
2021-11-08 19:17:39 +08:00
let win: BrowserWindow | null = null
2021-12-30 10:04:57 +08:00
async function createWindow() {
2021-11-08 19:17:39 +08:00
win = new BrowserWindow({
title: 'Main window',
webPreferences: {
preload: join(__dirname, '../preload/index.cjs')
},
})
if (app.isPackaged) {
2021-11-11 12:46:00 +08:00
win.loadFile(join(__dirname, '../renderer/index.html'))
2021-11-08 19:17:39 +08:00
} else {
const pkg = await import('../../package.json')
const url = `http://${pkg.env.HOST || '127.0.0.1'}:${pkg.env.PORT}`
win.loadURL(url)
2021-11-15 20:00:13 +08:00
win.webContents.openDevTools()
2021-11-08 19:17:39 +08:00
}
// Test active push message to Renderer-process.
2021-11-26 08:49:02 +08:00
win.webContents.on('did-finish-load', () => {
win?.webContents.send('main-process-message', (new Date).toLocaleString())
2021-11-26 08:49:02 +08:00
})
2021-11-08 19:17:39 +08:00
}
2021-12-30 10:04:57 +08:00
app.whenReady().then(createWindow)
2021-11-09 11:12:32 +08:00
2021-11-08 19:17:39 +08:00
app.on('window-all-closed', () => {
win = null
2021-11-09 11:12:32 +08:00
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('second-instance', () => {
if (win) {
2021-11-15 20:00:13 +08:00
// Someone tried to run a second instance, we should focus our window.
2021-11-09 11:12:32 +08:00
if (win.isMinimized()) win.restore()
win.focus()
}
2021-11-08 19:17:39 +08:00
})
2021-12-30 10:04:57 +08:00
app.on('activate', () => {
const allWindows = BrowserWindow.getAllWindows()
if (allWindows.length) {
allWindows[0].focus()
} else {
createWindow()
}
})