Electron
coderljw 2024-10-13 小于 1 分钟
# 1. 仅启动一个程序
if (!app.requestSingleInstanceLock()) {
app.quit()
return
}
app.on('second-instance', () => {
if (!mainWindow) return
if (mainWindow.isMinimized()) mainWindow.restore()
mainWindow.focus()
mainWindow.show()
})
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 2. 点击关闭最小化程序
mainWindow.on('close', e => {
e.preventDefault()
mainWindow.hide()
})
1
2
3
4
2
3
4
# 3. 开机自启
// 判断开机自启
app.getLoginItemSettings({ args: ['--openAsHidden'] }).openAtLogin
// 设置开机自启
app.setLoginItemSettings({
openAtLogin,
openAsHidden: true,
args: ['--openAsHidden'],
})
// 如果不是开机自启,最大化显示程序
mainWindow = new BrowserWindow({
show: false,
})
mainWindow.on('ready-to-show', () => {
if (!process.argv.includes('--openAsHidden')) {
mainWindow.maximize()
mainWindow.show()
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 4. 点击托盘
tray.on('click', () => {
if (mainWindow.isVisible()) {
if (mainWindow.isMinimized()) {
mainWindow.restore()
mainWindow.focus()
} else {
mainWindow.focus()
}
} else {
mainWindow.maximize()
mainWindow.show()
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 5. 自动更新
import type { BrowserWindow } from 'electron'
import log from 'electron-log'
import { autoUpdater } from 'electron-updater'
const setupUpdate = (mainWindow: BrowserWindow) => {
log.transports.file.level = 'info'
autoUpdater.logger = log
autoUpdater.checkForUpdatesAndNotify()
autoUpdater.on('checking-for-update', () => {
mainWindow.webContents.send('update:checking')
})
autoUpdater.on('update-available', () => {
mainWindow.webContents.send('update:available', true)
})
autoUpdater.on('update-not-available', () => {
mainWindow.webContents.send('update:available', false)
})
autoUpdater.on('error', error => {
mainWindow.webContents.send('update:error', error)
})
autoUpdater.on('download-progress', ({ percent }) => {
mainWindow.webContents.send('update:progress', percent)
})
autoUpdater.on('update-downloaded', () => {
mainWindow.webContents.send('update:downloaded')
})
}
export default setupUpdate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35