I'm currently working on an application that works like a spotlight search. One of the features is to be able to call the search-bar with a keyboard shortcut (in this case ctrl + D). I'm using electron.js to create this. For creating the global shortcut I used the following:
app.whenReady().then(() => {
globalShortcut.register('CommandOrControl+D', () => {
if (mainWindow.isVisible() == false) {
mainWindow.show();
console.log("\nctrl + D was pressed\nmainWindow focused");
} else if (mainWindow.isVisible() == true) {
mainWindow.blur();
mainWindow.hide();
console.log("\nctrl + D was pressed\nmainWindow not focused")
}
})
})
During testing (using electron-forge), I would enter the command electron-forge start
to run the program temporarily, and it worked perfectly, but after running electron-forge make
and running the exe file, the shortcut no longer works to hide/blur the window, however it does work to summon the window.
I tried changing the ctrl + D command to ctrl + X (recommended by electron) and several others and re-making the project to make sure the shortcut wasn't in use, but no luck. I had also began with isFocused instead of isVisible which didn't work either, even in testing.
Note: I am using Windows 10, which can operate differently than Mac when using electron at times, though it really shouldn't make a difference regarding this issue.
This is a very strange glitch, but I managed to get it to work. Nothing is wrong with Electron Forge. It turns out that isVisible
isn't very reliable in it's output, so by replacing this with isFocused
, it works perfectly. This also means that mainWindow.hide()
can be removed.
I also found that many shortcuts taken by windows itself or other programs can mess with results (pretty obvious but still good to note), and the Super Key (Windows Key) doesn't work due to it being mainly used for system level programs.