首页 > 其他 > 详细

Electron中通过globalShortcut实现监听键盘事件进而实现快捷键功能

时间:2020-06-03 22:28:08      阅读:48      评论:0      收藏:0      [点我收藏+]

场景

用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

技术分享图片

 技术分享图片

 

Electron中通过globalShortcut实现监听键盘事件进而实现快捷键功能

原文:https://www.cnblogs.com/badaoliumangqizhi/p/13040280.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!