【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])
    },
相关推荐
IT_陈寒16 分钟前
SpringBoot自动配置的坑,我的Bean怎么不生效?
前端·人工智能·后端
迷途呀28 分钟前
新闻头条后端:新闻缓存模块
前端·redis·python·缓存·fastapi
糖墨夕39 分钟前
第一章:为什么你要学 AI Agent?—— 从"切图仔"到全栈的进化之路
前端·javascript·vue.js
随风一样自由43 分钟前
【前端+Canvas+航天】长征十号乙火箭回收全流程动画
前端·canvas·长征十号乙
自律懒人1 小时前
ChatGPT Work 上线当天实测:GPT-5.6 Sol 把 Codex 塞进桌面应用,跨应用自动做报表和 PPT,一个指令干 3 小时的活
javascript·开源
CappuccinoRose1 小时前
CSS、Less、Sass(含 SCSS)、Stylus
前端·css·less·sass·stylus
不听话坏10 小时前
Ignition篇(下 一) 动态执行前的事情
开发语言·前端·javascript
likeyi0710 小时前
require 和 import的区别
开发语言·前端
pany11 小时前
做 AI 友好的开源 Vue3 模板 🌈
前端·vue.js·ai编程
小二·11 小时前
React 19 + Next.js 15 现代前端开发实战:App Router / Server Components / 流式渲染
前端·javascript·react.js