Electron单实例与APP唤醒

前言

如果我们在打开应用后,又点击应用的快捷方式,默认会再打开一个,这不是我们想实现的。

我们想出现的是以下两种方式

  1. 新的应用忽略,保持应用只有一个
  2. 直接打开现有应用的窗口

不做操作

1
2
3
4
5
6
const {app} = require("electron");
const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
app.quit();
}

唤醒窗口

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
const { app } = require('electron')
let loginWindow = null
let classcenterWin = null

const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit()
} else {
app.on('second-instance', (event, commandLine, workingDirectory) => {
// 当要打开第二个实例的时候 打开我们的窗口
if (loginWindow && !loginWindow.isDestroyed()) {
if (loginWindow.isMinimized()) {
loginWindow.restore()
}
loginWindow.focus()
}

if (classcenterWin && !classcenterWin.isDestroyed()) {
if (classcenterWin.isMinimized()) {
classcenterWin.restore()
}
classcenterWin.focus()
}
})

// 其它事件
app.on('ready', () => {
})
}

说明:

事件: ‘second-instance’

返回:

  • event Event
  • argv string[] - 第二实例命令行参数的数组。
  • workingDirectory string - 第二实例的工作目录。
  • additionalData unknown - 第二个实例发送过来的额外的 JSON 对象

当第二个实例被执行并且调用 app.requestSingleInstanceLock() 时,这个事件将在你的应用程序的首个实例中触发