Martijn Van Loocke
Martijn Van Loocke

Reputation: 533

How to focus on Electron window when it opens after focussing on another program

I'm creating an Electron app that should show itself when a global shortcut key is pressed. For the shortcut key, I'm using iohook and that part works well. If I allow the window to be shown as normally during startup of the app, Windows focusses on it (my test is pressing alt to see which menu bar is activated).

The problem is that if I start the program with visible: false or do not generate the Electron.BrowserWindow yet, and then call win.show() or create the window when I press the shortcut key, it opens the window in the foreground but the focus is still on the app that I was on before pressing the shortcut.

I have fixed this in the past with Autohotkey but I want to make this app cross-platorm and preferably contain as much of my code as possible within NodeJS.

Upvotes: 8

Views: 15990

Answers (1)

Martijn Van Loocke
Martijn Van Loocke

Reputation: 533

Turns out there is a delay in the OS before the window can be focussed on. Calling focus() immediately after show() does nothing (or may in some cases if it wins the race conditions). Using the show event to trigger the focus solves this.

win.on('show', () => { win.focus(); });
win.show();

EDIT: There still seems to be a race condition on the OS level that sometimes causes the window not to be focussed so I still have to add the timeout:

win.on('show', () => {
  setTimeout(() => {
    win.focus();
  }, 200);
});

Upvotes: 11

Related Questions