我刚刚制作了我的第一个Electron应用程序。但我注意到我的应用程序的3个服务随时在后台运行。当应用程序被全局键盘快捷键激活时,一个实例将移动到活动的应用程序部分。
退出时,只有一个实例消失而另外两个实例仍在运行。如果不从任务管理器手动停止这些服务,我无法再次启动应用程序。
app.js
const { app, BrowserWindow, globalShortcut } = require("electron");
const path = require("path");
const url = require("url");
let win = null;
var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
// Someone tried to run a second instance, we should focus our window.
if (win) {
win.show();
}
});
if (shouldQuit) {
app.quit();
return;
}
app.on("ready", () => {
win = new BrowserWindow({
width: 1000,
height: 600,
transparent: true,
frame: false
});
win.on("close", () => {
win = null;
});
win.loadURL(
url.format({
pathname: path.join(__dirname, "app", "index.html"),
protocol: "file",
slashes: true
})
);
win.once('ready-to-show', () => {
win.show()
});
win.on("blur", () => {
win.hide();
});
win.on('window-all-closed', () => {
globalShortcut.unregisterAll();
if (process.platform !== 'darwin') {
app.quit()
}
});
const ret = globalShortcut.register('CommandOrControl+L', () => {
if(win == null) {
globalShortcut.unregisterAll();
return;
}
win.show();
});
if (!ret) {
console.log('registration failed')
}
app.on('will-quit', () => {
// Unregister all shortcuts.
globalShortcut.unregisterAll();
});
app.on('before-quit', () => {
win.removeAllListeners('close');
globalShortcut.unregisterAll();
win.close();
});
});
我遇到的上一个错误是GlobalShortcut在关闭时未取消注册,因此我将其添加到 before-quit 和 window-all-closed 事件中。这解决了它。
编辑: 上述问题仅发生在生产代码上。在开发期间,所有3个实例一起关闭。我使用的是Windows 10和Electron 1.6.11。
答案 0 :(得分:0)
只需将其添加到您的主要javascript文件中,其中包含电子模块
app.on('window-all-closed', () => {
app.quit()
})