electron功能实现---添加全局快捷键、开机自启、选择安装路径

一、注册全局快捷键

采用globalShortcut,是主进程

ps:快捷键方式是全局的‘即使应用程序没有键盘焦点,它也仍然在持续监听键盘事件。在app模块的ready事件就绪之前,这个模块不能使用。

import {
  app,
  BrowserWindow,
  ipcMain,
  globalShortcut,
} from "electron";

  // 主窗口函数
createMainWindow() {
    globalShortcut.register("ctrl+F5", () => {
      app.relaunch();
      app.exit();
    });
    globalShortcut.register("ctrl+F4", () => {
      this.mainWindow?.reload();
    });
    globalShortcut.register("ctrl+F6", () => {
      app.exit();
    });
    globalShortcut.register("F11", () => {
      // 是否全屏
      if (this.mainWindow?.isFullScreen()) {
        // this.mainWindow?.minimize();
        this.mainWindow?.setFullScreen(false);
        this.mainWindow?.setMenuBarVisibility(true);
      } else {
        this.mainWindow?.setFullScreen(true);
        this.mainWindow?.setMenuBarVisibility(false);
      }
    });
    globalShortcut.register("ctrl+F12", () => {
      this.mainWindow?.webContents.openDevTools({ mode: "detach" });
    });
}

app.on('will-quit', () => {
  // 注销快捷键
  globalShortcut.unregister('CommandOrControl+X')

  // 注销所有快捷键
  globalShortcut.unregisterAll()
})

二、开机自启

在主进程实现

electron加入开机启动项最核心的代码是:

app.setLoginItemSettings();

function onAppReady() {
  new InitWindow().initWindow();
  // 设置开机自起
  const exeName = path.basename(process.execPath);
  app.setLoginItemSettings({
    // 设置为true注册开机自起
    openAtLogin: false, /
    openAsHidden: false,  //macOs
    path: process.execPath,
    args: ["--processStart", `"${exeName}"`], 
  });
}
app.isReady() ? onAppReady() : app.on("ready", onAppReady);

settings是个object类型,其key有:

  • openAtLogin:Boolean(可选)为true时,开启开机自启动功能,默认为false。
  • openAsHidden:Boolean(可选)。在os系统中因为没有args参数,才使用该属性实现。为true时表示以隐藏的方式启动应用。默认为false,开机会启动并弹出该应用窗口,并不友好。该属性在windows系统中的实现方式如下:
args: ["--openAsHidden"]

设置开机启动时,在args中传入--openAsHidden,这个字符串可以随便更改。获取开机启动时,也要在args中传入同样的字符串,不然获取不到正确的值。

然后在显示主窗口时,先判断一下process.argv中是否包含--openAsHidden,如果包含,说明是开机自动启动的,这时候不显示窗口;相反 如果不包含--openAsHidden的话,说明是用户手动启动软件,这时正常显示窗口就好了:

win.once("ready-to-show", () => {
  if (process.argv.indexOf("--openAsHidden") < 0) 
      win.show();
});
  • path:string(可选),windows在登录时启动的可执行文件 ,默认为process.execPath。
  • args:strng windows:要传递给可执行文件的命令行参数,默认使用空数组。注意用引号将路径换行。

如果需要在 Windows 上使用Squirrel的 autoUpdater ,你需要将启动路径设置为 Update.exe,并传递指定应用程序名称的参数。 例如:

const appFolder = path.dirname(process.execPath)
const updateExe = path.resolve(appFolder, '..', 'Update.exe')
const exeName = path.basename(process.execPath)

app.setLoginItemSettings({
  openAtLogin: true,
  path: updateExe,
  args: [
    '--processStart', `"${exeName}"`,
    '--process-start-args', `"--hidden"`
  ]
})