本文已参与「新人创作礼」活动, 一起开启掘金创作之路。
一、前言
本文主要介绍electron应用如何注册销毁快捷键、以及如何动态更换快捷键的方式。在一个桌面应用中,快捷键是必不可少的,因为这会极大地方便用户的操作,使之体验更加快捷、美好。
二、实施方案
1.注册快捷键
根据查看electron官方文档,我们可以很快的找到对应快捷键的模块,点击查看详情,其中部分内容如下
globalShortcut
模块可以在操作系统中注册/注销全局快捷键, 以便可以为操作定制各种快捷键。
注意: 快捷方式是全局的; 即使应用程序没有键盘焦点, 它也仍然在持续监听键盘事件。 在 app 模块的 ready
事件就绪之前,这个模块不能使用。
// 之前文章提到过得记录日志的工具
import log from './ElectronLog'
const { app, globalShortcut } = require('electron')
app.whenReady().then(() => {
// 注册一个'CommandOrControl+X' 快捷键监听器
const ret = globalShortcut.register('CommandOrControl+X', () => {
// 如果注册成功了,当用户按下该快捷键时,会执行这里的内容
console.log('用户按下了 CommandOrControl+X')
})
if (!ret) {
log.warning('CommandOrControl+X -- 快捷键注册失败')
}
// 检查快捷键是否注册成功
console.log(globalShortcut.isRegistered('CommandOrControl+X'))
})
这里我们在程序的ready
事件之后去注册快捷键。但是一般情况下,如果我们的应用不希望用户一打开就能使用一些快捷键的话,比如说我们希望用户在登陆成功之后才可以使用截图快捷键,如果遇到这种情况,我们可以在主进程中添加一个注册监听,如下
import { ipcMain, globalShortcut } from 'electron'
// 监听登录成功
ipcMain.on('login', (event, arg) => {
// 设置快捷键-截图
globalShortcut.register('CommandOrControl+Alt+d', () => {
// do something
})
})
2.注销快捷键
这个事情在electron官网中也有写到点击查看详情,具体书写方式如下
const { app, globalShortcut } = require('electron')
app.on('will-quit', () => {
// 注销快捷键
globalShortcut.unregister('CommandOrControl+X')
// 注销所有快捷键
globalShortcut.unregisterAll()
})
我们在应用退出的时候调用globalShortcut.unregisterAll()
这个方法就可以了,该方法会注销所有的全局快捷键(清空该应用程序的所有全局快捷键)。
如果不手动清除这些快捷键的话,它们会一直存在下去,有可能导致其他程序的快捷键无法使用。
3.动态更改快捷键
延续上面的说,比如说你的应用有截图这个功能,我们给了用户默认的截图快捷键指令,一般在应用设置中,也会在多出来一个快捷键设置,如图
这里我们就来讲讲,这里是怎么实现的, 但在这之前,要先说明一下,因为截图快捷键这种数据,一般是存储在用户本地的,所以这里我们要引用一个插件localforage,将数据存入本地数据库中。 安装方式在之前讲【Electron】vue+electron实现图片视频本地缓存的时候讲过, 如此配置下
// 创建一个本地用户数据库表
import localforage from 'localforage'
window.$useInfo = localforage.createInstance({
name: 'useInfo'
})
这里大家也可以使用别的方法,如果要存入到后端数据库的话,就直接调接口就好了。
之后我们开始写页面
// ShortcutKeySettings.vue
<template>
<div class="privacy-settings">
<h3 class="ps-title">快捷键管理</h3>
<ul class="ps-content">
<li class="ps-setting">
<div class="title">截图</div>
<div class="content">
<Input class="iconfont" v-model="content" style="width:320px;" clearable maxlength="0" :placeholder="placeholder" @on-focus="inputFocus()" @on-blur="inputBlur()" @on-keydown="getShortKeys" />
</div>
</li>
</ul>
</div>
</template>
<script>
const ipcRenderer = window.require('electron').ipcRenderer
export default {
name: 'ShortcutKeySettings',
components: {
},
data () {
return {
placeholder: '点击设置快捷键',
content: null,
keyIndex: -1,
oldKeys: ''
}
},
created () {
window.$isMac = /macintosh|mac os x/i.test(navigator.userAgent)
this.init()
},
methods: {
async init () {
// 获取之前用户设置的截图快捷键
let ScreenShotsKeys = await window.$useInfo.getItem('ScreenShotsKeys')
// 若之前用户没有设置,则使用默认的
if (!ScreenShotsKeys) {
ScreenShotsKeys = 'CommandOrControl+Alt+d'
}
this.oldKeys = ScreenShotsKeys
// '\ue672'这个字符是UI给做的mac的媒体键,即meta按键,若没有可以直接用meta代替
this.content = ScreenShotsKeys.replace('CommandOrControl', '\ue672')
},
// 设置组合键更换placeholder
inputFocus (index) {
this.placeholder = '键盘按下要设置的快捷键组合'
},
// 设置组合键更换placeholder
inputBlur () {
this.placeholder = '点击设置快捷键'
const formatKeys = this.content.replace('\ue672', 'CommandOrControl')
const keyArr = formatKeys.split('+')
if (formatKeys && keyArr.slice(-1)[0].trim()) {
// 将设置好的截图快捷键发送给主进程,让其重新设置
let params = {
new: formatKeys,
old: oldKeys
}
ipcRenderer.send('setShortKeys', params)
window.$useInfo.setItem(formatKeys)
}
},
// 获取组合按键
getShortKeys (e) {
e.preventDefault();
// ====== 禁止上下左右按键 ===== start
const list = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];
if(list.includes(e.key)) return;
// ====== 禁止上下左右按键 ===== end
const str = this.content
// 获取用户有没有按下特殊按键【'Control', 'Alt', 'Shift', 'Meta'】
const auxiliaryKey = [(e.ctrlKey ? 'Ctrl' : ''), (e.altKey ? 'Alt' : ''), (e.shiftKey ? 'Shift' : ''), (e.metaKey ? '\ue672' : '')].filter(t => t)
const someKeys = ['Control', 'Alt', 'Shift', 'Meta']
// mac下禁止使用快捷键option
let publicKey = someKeys.indexOf(e.key) < 0 ? e.key.toLocaleUpperCase() : ''
if(window.$isMac && e.altKey) {
publicKey = ''
}
if (auxiliaryKey.length) {
this.content = auxiliaryKey.join('+') + '+' + publicKey
} else {
this.content = str.substring(0, str.lastIndexOf('+') + 1) + publicKey
}
}
}
}
</script>
<style lang="less" scoped>
.privacy-settings {
width: 100%;
height: 100px;
.ps-title {
// width: 80px;
height: 24px;
font-size: 16px;
font-family: PingFangSC, PingFangSC-Medium;
font-weight: 500;
text-align: left;
color: #1f2329;
line-height: 24px;
}
.ps-content {
width: 100%;
padding-top: 12px;
/deep/.ivu-input {
font-family: iconfont!important;
}
li {
padding: 12px 0;
}
}
.ps-setting {
.title {
height: 22px;
font-size: 14px;
font-family: PingFangSC, PingFangSC-Medium;
font-weight: 500;
text-align: left;
color: #2b2f36;
line-height: 22px;
margin-bottom: 8px;
}
}
}
</style>
在主进程中监听
// 修改截图快捷键
ipcMain.on('setShortKeys', (e, data) => {
// 注销快捷键
globalShortcut.unregister(data.old)
// 设置快捷键
globalShortcut.register(data.new, () => {
// 调用截图方法
})
})
以上 我们就实现了快捷键的动态设置了!
三、后记
这里主要是为了嘱咐几句,快捷键一定要记得注销!退出就注销!一定要记得!
本篇完结! 撒花! 谢谢观看!希望对你有帮助!