electron中引入iohook来监听系统级鼠标键盘事件

最新做法:(2022-07-14记录)

npm install iohook@latest--save

安装好之后

直接使用会报错,这时候发现是缺少一些关于electron的编译,从以下地址选择对应系统的编译包手动放进去即可

Releases · wilix-team/iohook · GitHub

iohook官网:Usage | iohook

https://nodejs.ctolib.com/article/releases/98298

本人项目的版本号:electron5.0.0 node 12.16.1

一、准备工作

使用node-abi来获取electron和node对应的abi版本

npm install node-abi --save-dev
console.log(nodeAbi.getAbi('12.16.1','node'))// 68
    console.log(nodeAbi.getAbi('5.0.0','electron'))// 70
    console.log(nodeAbi.getTarget('68','node'))// 12.0.0
    console.log(nodeAbi.getTarget('70','electron'))//5.0.0

在使用中发现68的版本并不可以,因此使用了72

二、electron中安装iohook

npm install iohook@0.6.5 --save-dev

在package.json中配置一些内容

"iohook": {
    "targets": [
      "node-72",
      "electron-70"
    ],
    "platforms": [
      "win32",
      "darwin",
      "linux"
    ],
    "arches": [
      "x64",
      "ia32"
    ]
  }

重新编译的写法:

"rebuildnew": "npm rebuild --runtime=electron --target=5.0.0 --disturl=https://atom.io/download/atom-shell --abi=70"

三、iohook的使用

const ioHook = require('iohook');

    ioHook.start(false);
    const eventHandler =function(type){
        switch (type) {
            case 'mouseclick':
                console.log('mouse is click!')
                break;
            case 'mousedown':
                console.log('mouse is press!')
                break;
            case 'mouseup':
                console.log('mouse is release!')
                break;
            case 'mousedrag':
                console.log('mouse is moving!')
                break;
            case 'mousedrag':
                console.log('mouse is moving!')
                break;
            case 'mousewheel':
                console.log('keybord is rolling!')
                break;
            case 'keydown':
                console.log('keybord is press!')
                break;
            default:
                console.log('move mouse or keyboard try it!')
                break;
        }
    }
    ioHook.start(false);
    ioHook.on('mouseclick', ()=>{eventHandler('mouseclick')});
    ioHook.on('mousedown', ()=>{eventHandler('mousedown')});
    ioHook.on('mouseup', ()=>{eventHandler('mouseup')});
    ioHook.on('mousedrag', ()=>{eventHandler('mousedrag')});
    ioHook.on('mousewheel', ()=>{eventHandler('mousewheel')});
    ioHook.on('mouse', ()=>{eventHandler('mousedrag')});
    ioHook.on('keyup', ()=>{eventHandler('keyup')});
    ioHook.on('keydown', ()=>{eventHandler('keydown')});



app.on('before-quit', () => {
    // 卸载iohook监听
    ioHook.unload();
    ioHook.stop();
});


版权声明:本文为hhy1006894859原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。