Omar Tadjerouna
Omar Tadjerouna

Reputation: 1

Mousetrap.bind event fires on all open windows in Electron app

I'm using Electron to develop a desktop application and use Mousetrap to enable keyboard shortcuts. I want to close only the current active window when I press the ESC button. It works well when only one window is open. But when multiple windows are open, they all close simultaneously.

Here's the code I use on all my windows:

Mousetrap.bind('esc', function() { window.electron.ipcRenderer.sendMessage('closeWindow', 'windowName'); }, 'keyup');

Upvotes: 0

Views: 146

Answers (1)

Omar Tadjerouna
Omar Tadjerouna

Reputation: 1

I solved this problem by closing the focused window when the 'closeWindow' event is received in the main process.

In the renderer process:

Mousetrap.bind('esc', function() { window.electron.ipcRenderer.sendMessage('closeWindow'); }, 'keyup');

In the main process:

ipcMain.on('closeWindow', async (event, window) => {
  BrowserWindow.getFocusedWindow().close();
});

Upvotes: 0

Related Questions