【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])
    },
相关推荐
@PHARAOH7 分钟前
HOW - 实现 useClickOutside 或者 useClickAway
前端·javascript·react.js
_yingty_21 分钟前
GO语言入门经典-反射3(Value 与对象的值)
开发语言·前端·后端·学习·golang
糟糕好吃35 分钟前
如何用一个插件让你的 Taro 项目启动快 3 倍?
前端·javascript·微信小程序
糖墨夕1 小时前
【1】Three.js入门心得记-开发环境及准备工作
前端·three.js
前端_学习之路1 小时前
Vue--状态管理pinia
前端·javascript·vue.js
萌萌哒草头将军1 小时前
🔥🔥🔥MCP TypeScript SDK 初体验:挑战快速搭建一个 AI 应用!
前端·javascript·mcp
qq_316837751 小时前
uniapp 打包 H5 向 打包的APP 使用 @dcloudio/uni-webview-js 传值
开发语言·javascript·uni-app
冴羽yayujs1 小时前
SvelteKit 最新中文文档教程(19)—— 最佳实践之身份认证
前端·javascript·vue.js·react.js·前端框架·svelte·sveltekit
Dove言和1 小时前
vue-element-plus-admin的安装
前端·javascript·vue.js·element-plus
曾是惊鸿照影来1 小时前
vue2生成二维码海报,支持复制,下载
前端