electron#globalShortcut TypeScript Examples

The following examples show how to use electron#globalShortcut. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: main.ts    From DittoPlusPlus with MIT License 6 votes vote down vote up
function registerKeyboardShortcuts() {
  const res = globalShortcut.register('CommandOrControl+Shift+V', () => {
    toggleWindowVisibility();
  });

  if (!res) {
    //
  }
}
Example #2
Source File: main.dev.ts    From Oratio with MIT License 6 votes vote down vote up
app.on('window-all-closed', () => {
  // Respect the OSX convention of having the application in memory even
  // after all windows have been closed
  if (process.platform !== 'darwin') {
    app.quit();
  }
  globalShortcut.unregisterAll();
  server.close();
});
Example #3
Source File: main.dev.ts    From Oratio with MIT License 6 votes vote down vote up
app
  .whenReady()
  .then(createWindow)
  .then(() => {
    globalShortcut.register('CommandOrControl+O', () => {
      if (mainWindow?.isFocused()) {
        // Minimizing the window in a Windows OS returns focus to the original app
        // while hiding the app in a unix like OS returns focus
        if (process.platform === 'win32') {
          mainWindow?.minimize();
        } else {
          mainWindow?.hide();
        }
      } else {
        mainWindow?.show();
      }
    });

    server.listen(4563, () => {
      console.log(`Server running on http://localhost:4563`);
    });

    return mainWindow;
  })
  .catch(console.log);
Example #4
Source File: setting.ts    From Aragorn with MIT License 6 votes vote down vote up
toggleUploadShortcutKey(shortcutKey: string) {
    console.log(`toggle upload shortcut key: ${shortcutKey}`);
    const isOpened = this.configuration.openUploadShortcutKey;
    if (isOpened) {
      globalShortcut.unregister(shortcutKey);
      this.configuration.openUploadShortcutKey = false;
      this.configuration.uploadShortcutKey = shortcutKey;
      this.save();
      return { toggle: false, success: true };
    } else {
      const res = globalShortcut.register(shortcutKey, () => {
        UploaderManager.getInstance().uploadFromClipboard();
      });
      if (res) {
        this.configuration.openUploadShortcutKey = true;
        this.configuration.uploadShortcutKey = shortcutKey;
        this.save();
      } else {
        globalShortcut.unregister(shortcutKey);
      }
      return { toggle: true, success: res };
    }
  }
Example #5
Source File: setting.ts    From Aragorn with MIT License 6 votes vote down vote up
registerUploadShortcutKey() {
    if (this.configuration.openUploadShortcutKey) {
      const res = globalShortcut.register(this.configuration.uploadShortcutKey, () => {
        UploaderManager.getInstance().uploadFromClipboard();
      });
      if (res) {
        console.log('init register upload shortcut key success');
      } else {
        console.error('init register upload shortcut key failed');
      }
    }
  }
Example #6
Source File: main.ts    From tuxedo-control-center with GNU General Public License v3.0 6 votes vote down vote up
app.on('will-quit', (event) => {
    // Prevent default quit action
    event.preventDefault();

    // Close window but do not quit application unless tray is gone
    if (tccWindow) {
        tccWindow.close();
        tccWindow = null;
    }
    if (!tray.isActive()) {
        // Actually quit
        globalShortcut.unregisterAll();
        app.exit(0);
    }
});
Example #7
Source File: main.ts    From league-profile-tool with MIT License 5 votes vote down vote up
// Disable refresh
app.whenReady().then(() => {
  globalShortcut.register("CommandOrControl+R", () => {
  });
});
Example #8
Source File: main.ts    From DittoPlusPlus with MIT License 5 votes vote down vote up
function unRegisterKeyboardShortcuts() {
  globalShortcut.unregisterAll();
}
Example #9
Source File: shortcuts.ts    From awakened-poe-trade with MIT License 5 votes vote down vote up
function registerGlobal () {
  const toRegister = shortcutsFromConfig()
  for (const entry of toRegister) {
    const isOk = globalShortcut.register(shortcutToElectron(entry.shortcut), () => {
      if (entry.keepModKeys) {
        const nonModKey = entry.shortcut.split(' + ').filter(key => !isModKey(key))[0]
        robotjs.keyToggle(nonModKey, 'up')
      } else {
        entry.shortcut.split(' + ').reverse().forEach(key => { robotjs.keyToggle(key, 'up') })
      }

      if (entry.action.type === 'toggle-overlay') {
        toggleOverlayState()
      } else if (entry.action.type === 'paste-in-chat') {
        typeInChat(entry.action.text, entry.action.send)
      } else if (entry.action.type === 'trigger-event') {
        overlaySendEvent({ name: entry.action.eventName, payload: entry.action.payload } as ipc.IpcEvent)
      } else if (entry.action.type === 'stash-search') {
        stashSearch(entry.action.text)
      } else if (entry.action.type === 'copy-item') {
        const { action } = entry

        const pressPosition = screen.getCursorScreenPoint()

        pollClipboard()
          .then(clipboard => {
            if (action.eventName === 'price-check-quick' || action.eventName === 'price-check-locked') {
              showPriceCheck({ clipboard, pressPosition, eventName: action.eventName })
            } else {
              overlaySendEvent({
                name: action.eventName,
                payload: { clipboard, position: pressPosition }
              })
              if (action.focusOverlay) {
                assertOverlayActive()
              }
            }
          }).catch(() => {})

        if (!entry.keepModKeys) {
          pressKeysToCopyItemText()
        } else {
          pressKeysToCopyItemText(entry.shortcut.split(' + ').filter(key => isModKey(key)))
        }
      }
    })

    if (!isOk) {
      logger.error('Failed to register a shortcut. It is already registered by another application.', { source: 'shortcuts', shortcut: entry.shortcut })
    }

    if (entry.action.type === 'test-only') {
      globalShortcut.unregister(shortcutToElectron(entry.shortcut))
    }
  }

  logger.verbose('Registered Global', { source: 'shortcuts', total: toRegister.length })
}
Example #10
Source File: shortcuts.ts    From awakened-poe-trade with MIT License 5 votes vote down vote up
function unregisterGlobal () {
  globalShortcut.unregisterAll()
  logger.verbose('Unregistered Global', { source: 'shortcuts' })
}
Example #11
Source File: main.dev.ts    From Oratio with MIT License 5 votes vote down vote up
createWindow = async () => {
  if (
    process.env.NODE_ENV === 'development' ||
    process.env.DEBUG_PROD === 'true'
  ) {
    await installExtensions();
  }

  const RESOURCES_PATH = app.isPackaged
    ? path.join(process.resourcesPath, 'assets')
    : path.join(__dirname, '../assets');

  const getAssetPath = (...paths: string[]): string => {
    return path.join(RESOURCES_PATH, ...paths);
  };

  mainWindow = new BrowserWindow({
    show: false,
    width: 860,
    height: 850,
    icon: getAssetPath('icon.png'),
    autoHideMenuBar: true,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true,
      // offscreen: true,
    },
  });

  mainWindow.loadURL(`file://${__dirname}/index.html#/home`);

  /**
   * Add event listeners...
   */

  // @TODO: Use 'ready-to-show' event
  //        https://github.com/electron/electron/blob/master/docs/api/browser-window.md#using-ready-to-show-event
  mainWindow.webContents.on('did-finish-load', () => {
    if (!mainWindow) {
      throw new Error('"mainWindow" is not defined');
    }
    if (process.env.START_MINIMIZED) {
      mainWindow.minimize();
    } else {
      mainWindow.show();
      mainWindow.focus();
    }
  });

  mainWindow.on('closed', () => {
    // mainWindow = null;
    if (process.platform !== 'darwin') {
      app.quit();
    }
    globalShortcut.unregisterAll();
    server.close();
  });

  const menuBuilder = new MenuBuilder(mainWindow);
  menuBuilder.buildMenu();

  // Open urls in the user's browser
  mainWindow.webContents.on('new-window', (event, url) => {
    event.preventDefault();
    shell.openExternal(url);
  });

  // Remove this if your app does not use auto updates
  // eslint-disable-next-line
  new AppUpdater();
}
Example #12
Source File: main.ts    From excalidraw-desktop with MIT License 5 votes vote down vote up
function createWindow() {
  mainWindow = new BrowserWindow({
    show: false,
    height: 600,
    width: 800,
    webPreferences: {
      contextIsolation: true, // protect against prototype pollution
      preload: `${__dirname}/preload.js`,
    },
  });

  if (argv.devtools) {
    mainWindow.webContents.openDevTools({mode: "detach"});
  }

  mainWindow.webContents.on("will-navigate", openExternalURLs);
  mainWindow.webContents.on("new-window", openExternalURLs);

  mainWindow.loadURL(
    url.format({
      pathname: EXCALIDRAW_BUNDLE,
      protocol: "file",
      slashes: true,
    }),
  );

  mainWindow.on("closed", () => {
    mainWindow = null;
  });

  // Enable Cmd+Q on mac to quit the application
  if (process.platform === "darwin") {
    globalShortcut.register("Command+Q", () => {
      app.quit();
    });
  }

  // calling.show after this event, ensure there's no visual flash
  mainWindow.once("ready-to-show", async () => {
    const versions = await checkVersion();

    console.info("Current version", versions.local);
    console.info("Needs update", versions.needsUpdate);

    setAppName(APP_NAME);
    setMetadata("versions", versions);
    setMetadata("appIconPath", APP_ICON_PATH);
    setupMenu(mainWindow);

    mainWindow.show();
  });
}
Example #13
Source File: index.ts    From electron with MIT License 5 votes vote down vote up
registerGlobalHotKey = () => {
  for (const hotKey of GlobalHotKey) {
    globalShortcut.register(hotKey.key, hotKey.active);
  }
}
Example #14
Source File: index.ts    From electron with MIT License 5 votes vote down vote up
unregisterGlobalHotKey = () => {
  globalShortcut.unregisterAll();
}
Example #15
Source File: main.ts    From tuxedo-control-center with GNU General Public License v3.0 4 votes vote down vote up
app.whenReady().then( async () => {
    try {
        const systemLanguageId = app.getLocale().substring(0, 2);
        if (await userConfig.get('langId') === undefined) {
            if (availableLanguages.includes(systemLanguageId)) {
                userConfig.set('langId', systemLanguageId);
            } else {
                userConfig.set('langId', availableLanguages[0]);
            }
        }
    } catch (err) {
        console.log('Error determining user language => ' + err);
        quitCurrentTccSession();
    }

    if (startTCCAccelerator !== 'none') {
        const success = globalShortcut.register(startTCCAccelerator, () => {
            activateTccGui();
        });
        if (!success) { console.log('Failed to register global shortcut'); }
    }

    tray.state.tccGUIVersion = 'v' + app.getVersion();
    tray.state.isAutostartTrayInstalled = isAutostartTrayInstalled();
    tray.state.primeQuery = primeSelectQuery();
    tray.state.isPrimeSupported = primeSupported();
    await updateTrayProfiles();
    tray.events.startTCCClick = () => activateTccGui();
    tray.events.exitClick = () => quitCurrentTccSession();
    tray.events.autostartTrayToggle = () => {
        if (tray.state.isAutostartTrayInstalled) {
            removeAutostartTray();
        } else {
            installAutostartTray();
        }
        tray.state.isAutostartTrayInstalled = isAutostartTrayInstalled();
        tray.create();
    };
    const messageBoxprimeSelectAccept = {
        type: 'question',
        buttons: [ 'yes', 'cancel' ],
        message: 'Change graphics configuration and shutdown?'
    };
    tray.events.selectNvidiaClick = () => {
        if (dialog.showMessageBoxSync(messageBoxprimeSelectAccept) === 0) { primeSelectSet('on'); }
    };
    tray.events.selectBuiltInClick = () => {
        if (dialog.showMessageBoxSync(messageBoxprimeSelectAccept) === 0) { primeSelectSet('off'); }
    };
    tray.events.profileClick = (profileName: string) => { setTempProfile(profileName); };
    tray.create();

    tray.state.powersaveBlockerActive = powersaveBlockerId !== undefined && powerSaveBlocker.isStarted(powersaveBlockerId);
    tray.events.powersaveBlockerClick = () => {
        if (powersaveBlockerId !== undefined && powerSaveBlocker.isStarted(powersaveBlockerId)) {
            powerSaveBlocker.stop(powersaveBlockerId);
        } else {
            powersaveBlockerId = powerSaveBlocker.start('prevent-display-sleep');
        }
        tray.state.powersaveBlockerActive = powerSaveBlocker.isStarted(powersaveBlockerId);
        tray.create();
    }

    if (!trayOnlyOption) {
        activateTccGui();
    }

    tccDBus = new TccDBusController();
    tccDBus.init().then(() => {
        if (!noTccdVersionCheck) {
            // Regularly check if running tccd version is different to running gui version
            const tccdVersionCheckInterval = 5000;
            setInterval(async () => {
                if (await tccDBus.tuxedoWmiAvailable()) {
                    const tccdVersion = await tccDBus.tccdVersion();
                    if (tccdVersion.length > 0 && tccdVersion !== app.getVersion()) {
                        console.log('Other tccd version detected, restarting..');
                        process.on('exit', function () {
                            child_process.spawn(
                                process.argv[0],
                                process.argv.slice(1).concat(['--tray']),
                                {
                                    cwd: process.cwd(),
                                    detached : true,
                                    stdio: "inherit"
                                }
                            );
                        });
                        process.exit();
                    }
                }
            }, tccdVersionCheckInterval);
        }

        tccDBus.consumeModeReapplyPending().then((result) => {
            if (result) {
                child_process.exec("xset dpms force off && xset dpms force on");
            }
        });
        tccDBus.onModeReapplyPendingChanged(() => {
            tccDBus.consumeModeReapplyPending().then((result) => {
                if (result) {
                    child_process.exec("xset dpms force off && xset dpms force on");
                }
            });
        });
    });

    const profilesCheckInterval = 4000;
    setInterval(async () => { updateTrayProfiles(); }, profilesCheckInterval);
});