From 7efe109c83b5cc4d3f5dd10135bfe26faff87260 Mon Sep 17 00:00:00 2001 From: qier222 Date: Fri, 19 Mar 2021 14:24:39 +0800 Subject: [PATCH] feat: support global shortcuts --- src/background.js | 18 +++++++++++++++++- src/electron/globalShortcut.js | 22 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/electron/globalShortcut.js diff --git a/src/background.js b/src/background.js index 6ca0bc9..1efb771 100644 --- a/src/background.js +++ b/src/background.js @@ -1,5 +1,12 @@ "use strict"; -import { app, protocol, BrowserWindow, shell, dialog } from "electron"; +import { + app, + protocol, + BrowserWindow, + shell, + dialog, + globalShortcut, +} from "electron"; import { createProtocol } from "vue-cli-plugin-electron-builder/lib"; import { startNeteaseMusicApi } from "./electron/services"; import { initIpcMain } from "./electron/ipcMain.js"; @@ -7,6 +14,7 @@ import { createMenu } from "./electron/menu"; import { createTray } from "@/electron/tray"; import { createTouchBar } from "./electron/touchBar"; import { createDockMenu } from "./electron/dockMenu"; +import { registerGlobalShortcut } from "./electron/globalShortcut"; import { autoUpdater } from "electron-updater"; import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer"; import express from "express"; @@ -214,6 +222,9 @@ class Background { // create touch bar this.window.setTouchBar(createTouchBar(this.window)); + + // register global shortcuts + registerGlobalShortcut(this.window); }); app.on("activate", () => { @@ -240,6 +251,11 @@ class Background { app.on("quit", () => { this.expressApp.close(); }); + + app.on("will-quit", () => { + // unregister all global shortcuts + globalShortcut.unregisterAll(); + }); } } diff --git a/src/electron/globalShortcut.js b/src/electron/globalShortcut.js new file mode 100644 index 0000000..76fa151 --- /dev/null +++ b/src/electron/globalShortcut.js @@ -0,0 +1,22 @@ +const { globalShortcut } = require("electron"); + +export function registerGlobalShortcut(win) { + globalShortcut.register("Alt+CommandOrControl+P", () => { + win.webContents.send("play"); + }); + globalShortcut.register("Alt+CommandOrControl+Right", () => { + win.webContents.send("next"); + }); + globalShortcut.register("Alt+CommandOrControl+Left", () => { + win.webContents.send("previous"); + }); + globalShortcut.register("Alt+CommandOrControl+Up", () => { + win.webContents.send("increaseVolume"); + }); + globalShortcut.register("Alt+CommandOrControl+Down", () => { + win.webContents.send("decreaseVolume"); + }); + globalShortcut.register("Alt+CommandOrControl+L", () => { + win.webContents.send("like"); + }); +}