【Electron】上下键切换消息

需求:

如图,需要监听上下键切换消息

  1. Electron 注册 全局快捷键【globalShortcut】监听 在focus注册 在blur 注销

    如苹果系统在使用某个软件(focus)时 右上角会有应用标题
    Electron 代码:
javascript 复制代码
win.on('focus', ()=>{
    globalShortcut.register('Up', () => {
        win.webContents.send('keyDown', { keyType: 'up'}) // 发送给前端页面
    })

    globalShortcut.register('Down', () => {
        win.webContents.send('keyDown', { keyType: 'down'})
    })
})
win.on('blur',()=>{
    globalShortcut.unregister('Up')
    globalShortcut.unregister('Down')
})

前端监听Electron IPC render发送的消息

javascript 复制代码
this.$ipc.removeAllListeners('keyDown');
this.$ipc.on('keyDown', (event, result) => {
  this.keyCodeUpDown(result)
})

其中 keyCodeUpDown 方法的代码如下:

javascript 复制代码
    keyCodeUpDown(result) {
      let index = 0;
      let currentIndex = this.conversationIdListMap[this.currentConversationId];
      // 都没有选
      if (!this.currentConversationId) {
        if (result.keyType == 'up') {
          index = this.conversationList.length - 1; // 最后一个
        }
        if (result.keyType == 'down') {
          index = 0; // 第一个
        }
      } else {
        if (result.keyType == 'up') {
          if (currentIndex == 0) {
            return;
          }
          index = currentIndex - 1
        }
        if (result.keyType == 'down') {
          if (currentIndex == (this.conversationList.length - 1)) {
            return;
          }
          index = currentIndex + 1
        }
      }
      // 如果没漏出来 自动滑过去
      let [currentDiv] = this.$refs['conversation-item-' + this.conversationList[index].conv_id]
      let bottom_diff = currentDiv.getBoundingClientRect().bottom - window.innerHeight // 元素底部到屏幕的距离
      let top_diff = currentDiv.getBoundingClientRect().top - 72 // 元素顶部距离
      if (bottom_diff > 0 && result.keyType == 'down') {
        this.$refs['conversation-list'].scrollTo(0, currentDiv.offsetTop - window.innerHeight + 75)
      }
      if (top_diff < 0 && result.keyType == 'up') {
        this.$refs['conversation-list'].scrollTo(0, currentDiv.offsetTop - 75)
      }
      this.toMessageDetail(this.conversationList[index])
    },
相关推荐
JunpengHu12 小时前
esri-leaflet介绍
前端
zm43512 小时前
bpmn.js 自定义绘制流程图节点
前端·bpmn-js
小杨梅君12 小时前
探索现代 CSS 色彩:从 HSL 到 OKLCH,打造动态色阶
前端·javascript·css
刺客_Andy12 小时前
React 第五十一节 Router中useOutletContext的使用详解及注意事项
前端·javascript·react.js
宁雨桥13 小时前
基于 Debian 服务器的前端项目部署完整教程
服务器·前端·debian
JunpengHu13 小时前
CSS 滤镜(filter)
前端
你说啥名字好呢13 小时前
【React Fiber的重要属性】
javascript·react.js·ecmascript
时雨__13 小时前
uniapp转鸿蒙app内部测试发布过程——踩坑记录
前端·harmonyos
去伪存真13 小时前
Android手机不支持文字转语音window.speechSynthesis API,怎么办?
前端
三年三月13 小时前
自建HTTPS证书
前端·javascript