场景

用HTML和CSS和JS构建跨平台桌面应用程序的开源库Electron的介绍以及搭建HelloWorld:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106413828

Electron怎样进行渲染进程调试和使用浏览器和VSCode进行调试:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106414541

在上面搭建好项目以及知道怎样进行调试后,那么Electron怎样实现系统快捷键。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

主进程实现键盘快捷键

globalShortcut模块可以向操作系统注册/注销全局键盘快捷方式,以便您可以自定义各种快捷方式的操作。

注:快捷方式是全局的,即使应用程序没有键盘焦点,它也能工作。

打开项目的main.js

引入globalShortcut模块

const {app, BrowserWindow,globalShortcut} = require('electron')

然后找到app.whenReady事件,将其修改为如下

app.whenReady().then(() => {
  createWindow();
  //注册Ctr+x事件
  const ret = globalShortcut.register('CommandOrControl+X', () => {
    console.log('CommandOrControl+X is pressed')
  })

  if (!ret) {
    console.log('registration failed')
  }

  // 验证是否注册成功
  console.log(globalShortcut.isRegistered('CommandOrControl+X'))
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

注:

首先通过globalShortcut.register注册ctrl+x的快捷键,然后通过globalShortcut.isRegistered获取是否注册成功快捷键。

然后再要在窗体关闭的事件中取消注册,同样在main.js中找到app.on('window-all-closed'

将其修改为

// Quit when all windows are closed.
app.on('window-all-closed', function () {
// Unregister a shortcut.
globalShortcut.unregister('CommandOrControl+X')

// Unregister all shortcuts.
globalShortcut.unregisterAll()
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') app.quit()
})

调试运行项目,点击快捷键ctrl+x,查看调试控制台输出

 

 

渲染进程快捷键

在渲染进程中实现快捷键,打开renderer.js

引入remote模块

const {remote} = require("electron");

然后通过remote调用globalShortcut

remote.globalShortcut.register("CommandOrControl+G",()=>{
  console.log("您按下了ctrl + G");
})

运行项目打开调试页面,按下快捷键ctrl+G

 

 

posted on 2020-06-03 21:52  霸道流氓  阅读(3492)  评论(0编辑  收藏  举报

Live2D