【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])
    },
相关推荐
华玥作者5 小时前
[特殊字符] VitePress 对接 Algolia AI 问答(DocSearch + AI Search)完整实战(下)
前端·人工智能·ai
Mr Xu_6 小时前
告别冗长 switch-case:Vue 项目中基于映射表的优雅路由数据匹配方案
前端·javascript·vue.js
前端摸鱼匠6 小时前
Vue 3 的toRefs保持响应性:讲解toRefs在解构响应式对象时的作用
前端·javascript·vue.js·前端框架·ecmascript
sleeppingfrog6 小时前
zebra通过zpl语言实现中文打印(二)
javascript
lang201509286 小时前
JSR-340 :高性能Web开发新标准
java·前端·servlet
好家伙VCC7 小时前
### WebRTC技术:实时通信的革新与实现####webRTC(Web Real-TimeComm
java·前端·python·webrtc
未来之窗软件服务7 小时前
未来之窗昭和仙君(六十五)Vue与跨地区多部门开发—东方仙盟练气
前端·javascript·vue.js·仙盟创梦ide·东方仙盟·昭和仙君
baidu_247438617 小时前
Android ViewModel定时任务
android·开发语言·javascript
嘿起屁儿整8 小时前
面试点(网络层面)
前端·网络
VT.馒头8 小时前
【力扣】2721. 并行执行异步函数
前端·javascript·算法·leetcode·typescript