Electron在mac下快捷键失效的问题及解决

场景:在消息发送的输入框中,使用快捷键的复制粘贴,全选,等等都会失效。

解决方案如下:

将如下代码放到main/index.js主进程中

mainWIndow = new BrowserWindow({}); 
if (process.platform === 'darwin') { let contents = mainWindow.webContents globalShortcut.register('CommandOrControl+C', () => { contents.copy() }) globalShortcut.register('CommandOrControl+V', () => { contents.paste() }) globalShortcut.register('CommandOrControl+X', () => { contents.cut() }) globalShortcut.register('CommandOrControl+A', () => { contents.selectAll() }) }

补充:在实践了上述方案,发现一个后续的问题,electron项目的快捷键可以使用了,但是一个更严重的问题是,系统本身的快捷键由于被electron全局注册,因此系统的快捷键失效。

面临这个问题的解决办法,我们进行以下方法修复

  mainWindow.on('focus', () => {
    // mac下快捷键失效的问题
    if (process.platform === 'darwin') {
      let contents = mainWindow.webContents
      globalShortcut.register('CommandOrControl+C', () => {
        console.log('注册复制快捷键成功')
        contents.copy()
      })

      globalShortcut.register('CommandOrControl+V', () => {
        console.log('注册粘贴快捷键成功')
        contents.paste()
      })

      globalShortcut.register('CommandOrControl+X', () => {
        console.log('注册剪切快捷键成功')
        contents.cut()
      })

      globalShortcut.register('CommandOrControl+A', () => {
        console.log('注册全选快捷键成功')
        contents.selectAll()
      })
    }
  })
  mainWindow.on('blur', () => {
    globalShortcut.unregisterAll() // 注销键盘事件
  })

思路:在窗口获取焦点的时候注册快捷键,在窗口失去焦点的时候注销electron的快捷键即可。

 

posted @ 2020-04-15 16:35  狗尾草的博客  阅读(1482)  评论(0编辑  收藏  举报