我刚刚在 Github 上发布了一个名为 Popup Window 的 Electron 测试应用程序,它展示了如何正确地将焦点返回到上一个窗口。它是我之前的一个项目的简化版本,仅适用于 macOS。我遇到了与您完全相同的问题,我记得我通过隐藏应用程序而不是窗口来解决它,并处理窗口模糊事件以实际隐藏它......
HTH...
main.js:
const { app, BrowserWindow, globalShortcut, ipcMain } = require ('electron');
let mainWindow = null;
function onAppReady ()
{
mainWindow = new BrowserWindow
(
{
width: 600,
height: 600,
show: false,
frame: false
}
);
mainWindow.loadURL (`file://${__dirname}/index.html`);
mainWindow.once ('closed', () => { mainWindow = null; });
mainWindow.on ('blur', () => { mainWindow.hide (); });
globalShortcut.register ("CommandOrControl+Alt+P", () => { mainWindow.show (); });
ipcMain.on ('dismiss', () => { app.hide (); });
}
app.once ('ready', onAppReady);
app.once ('window-all-closed', () => { app.quit (); });
app.dock.hide ();
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<!-- All of the Node.js APIs are available in this renderer process. -->
We are using Node.js <script>document.write(process.versions.node)</script>,
Chromium <script>document.write(process.versions.chrome)</script>,
and Electron <script>document.write(process.versions.electron)</script>.
<script>
// You can also require other files to run in this process
require('./renderer.js')
</script>
</body>
</html>
renderer.js:
const { ipcRenderer } = require ('electron');
document.addEventListener
(
'keydown',
(event) =>
{
if (event.key === 'Enter')
{
event.preventDefault ();
ipcRenderer.send ('dismiss');
}
}
);