Let's start with the simplest case, and then build our solution to better handle some cases of edges.
The simplest case is to show a window that is already open when the global shortcut that we registered is clicked.
const path = require('path'); const { app, BrowserWindow, globalShortcut } = require('electron'); let mainWindow = null; app.on('ready', () => { mainWindow = new BrowserWindow(); mainWindow.loadURL(path.join(__dirname, 'index.html')); const shortcut = globalShortcut.register('Control+Space', () => { mainWindow.show(); }); if (!shortcut) { console.log('Registration failed.'); } });
This code has some problems. The good news is that it still works if the window has been minimized. The bad news is that it will not work if the window is closed. This is because closing the last window terminates the application. Bummer. (Honestly, I was a little surprised by this, but what happens. So, let it go.)
Stop for this to happen.
app.on('window-all-closed', (event) => { event.preventDefault(); });
Ok, our application does not quit, but it will work.
Uncaught Exception: Error: Object has been destroyed
Good Excellent. This is because the window is destroyed when it closes. Therefore, do not close it. Let him hide it, right? Within app.on('ready', () => {…}) add the following:
mainWindow.on('close', (event) => { event.preventDefault(); mainWindow.hide(); });
The end result is as follows:
const path = require('path'); const { app, BrowserWindow, globalShortcut } = require('electron'); let mainWindow = null; app.on('ready', () => { mainWindow = new BrowserWindow(); mainWindow.loadURL(path.join(__dirname, 'index.html')); const shortcut = globalShortcut.register('Control+Space', () => { mainWindow.show(); }); if (!shortcut) { console.log('Registration failed.'); } mainWindow.on('close', (event) => { event.preventDefault(); mainWindow.hide(); }); }); app.on('window-all-closed', (event) => { event.preventDefault(); });
And with that, you should have basic functionality. You click your global shortcut and a window appears. Unplug it and press the keys and see how it appears.