【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])
    },
相关推荐
四瓣纸鹤几秒前
闭包到底是啥?
javascript·闭包
全栈技术负责人7 分钟前
我的大前端世界观 (黄玄 - FEDAY 2023)
前端
changlianzhifu19 分钟前
分账系统:从“资金管道“到“增长引擎“,重塑商业价值分配新范式
java·服务器·前端
异界蜉蝣11 分钟前
前端模块化的演进史:从混乱到秩序
前端
宠..12 分钟前
QButtonGroup
java·服务器·开发语言·前端·数据库·c++·qt
写代码的【黑咖啡】17 分钟前
Python中的文件操作详解
java·前端·python
Moment19 分钟前
一文搞懂 Tailwind CSS v4 主题变量映射背后的原理
前端·javascript·面试
我命由我1234521 分钟前
JavaScript WebGL - WebGL 引入(获取绘图上下文、获取最大支持纹理尺寸)
开发语言·前端·javascript·学习·ecmascript·学习方法·webgl
辛-夷23 分钟前
2025年高频面试题整理(vue系列一)
前端·javascript·vue.js·前端框架
GISer_Jing23 分钟前
ByteDance AI战略:前端生态的颠覆者
前端·人工智能·aigc