ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

【Electron】上下键切换消息

【Electron】上下键切换消息

需求:
![在这里插入图片描述](https://img-blog.csdnimg.cn/bd832900cae64f8d8bd3e85e4c474ec5.png
如图,需要监听上下键切换消息

  1. Electron 注册 全局快捷键【globalShortcut】监听 在focus注册 在blur 注销
    在这里插入图片描述
    如苹果系统在使用某个软件(focus)时 右上角会有应用标题
    Electron 代码:
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发送的消息

this.$ipc.removeAllListeners('keyDown');
this.$ipc.on('keyDown', (event, result) => {this.keyCodeUpDown(result)
})

其中 keyCodeUpDown 方法的代码如下:

    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])},
返回列表