当前位置: 代码迷 >> 综合 >> Electron.js指南——键盘快捷键
  详细解决方案

Electron.js指南——键盘快捷键

热度:39   发布时间:2024-03-06 09:15:05.0

键盘快捷键

配置本地和全局键盘快捷键

本地快捷方式

您可以使用“菜单”模块配置仅在应用程序集中时才会触发的键盘快捷键。为此,请accelerator在创建MenuItem时指定一个 属性。

const { Menu, MenuItem } = require('electron') const menu = new Menu()menu.append(new MenuItem({label: 'Print',accelerator: 'CmdOrCtrl+P',click: () => { console.log('time to print stuff') } })) 
您可以根据用户的操作系统配置不同的组合键。
{accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Ctrl+Shift+I' } 
全球捷径

即使应用程序没有键盘焦点,也可以使用globalShortcut模块检测键盘事件。

const { app, globalShortcut } = require('electron')app.whenReady().then(() => {globalShortcut.register('CommandOrControl+X', () => {console.log('CommandOrControl+X is pressed')}) }) 
BrowserWindow内的快捷方式

如果要处理BrowserWindow的键盘快捷键,则可以在渲染器进程内的窗口对象上使用keyupkeydown事件侦听器。

window.addEventListener('keyup', doSomething, true) 
请注意第三个参数true,这意味着侦听器将始终在其他侦听器之前收到按键,因此他们无法对其进行stopPropagation()调用。

before-input-event事件在分派keydownkeyup页面中的事件之前发出。它可用于捕获和处理菜单中不可见的自定义快捷方式。

如果您不想进行手动快捷键解析,则可以使用一些库进行高级键检测,例如mousetrap。

Mousetrap.bind('4', () => { console.log('4') }) Mousetrap.bind('?', () => { console.log('show shortcuts!') }) Mousetrap.bind('esc', () => { console.log('escape') }, 'keyup')// combinations Mousetrap.bind('command+shift+k', () => { console.log('command shift k') })// map multiple combinations to the same callback Mousetrap.bind(['command+k', 'ctrl+k'], () => {console.log('command k or control k')// return false to prevent default behavior and stop event from bubblingreturn false })// gmail style sequences Mousetrap.bind('g i', () => { console.log('go to inbox') }) Mousetrap.bind('* a', () => { console.log('select all') })// konami code! Mousetrap.bind('up up down down left right left right b a enter', () => {console.log('konami code') })