Bringing an electron app to foreground with a global shortcut (like Spotlight/Launchy)

前端 未结 1 1748
南旧
南旧 2021-02-03 12:57

I\'m looking to replicate behavior similar to that of Launchy/Quicksilver/Spotlight.

I want to have an electron app that\'s always running. When I hit a shortcut key, t

相关标签:
1条回答
  • 2021-02-03 13:36

    Let's start with the simplest case and then build our solution to better handle some edge cases.

    The simplest possible case is to show a window that is already open whenever the global shortcut we registered is pressed.

    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 though. 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 has been closed. This is because closing the last window quits the application. Bummer. (Frankly, I was a little surprised by this—but that's what happens. So, let's go with it.)

    Let's stop that from happening.

    app.on('window-all-closed', (event) => {
      event.preventDefault();
    });
    

    Okay, our app doesn't quit, it but it crashes.

    Uncaught Exception:
    Error: Object has been destroyed
    

    Alright, fine. This is because the window is destroyed when it's close. So, let's not close it. Let's hide it, shall we? Within app.on('ready', () => {…}), add the following:

    mainWindow.on('close', (event) => {
      event.preventDefault();
      mainWindow.hide();
    });
    

    The end result looks like this:

    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 the basic functionality in place. You press your global shortcut and the window appears. Dismiss it and press the keys and watch it reappear.

    0 讨论(0)
提交回复
热议问题