robotjs帮我们实现第三步,首先是API文档
安装robotjs
再electron里输入process.versions
查到node的版本
先查询abi
//手动编译
npm rebuild —runtime=electron—disturl=https:/latom.io/download/atom-shell
—target=<electron版本>—abi=<对应版本abi>
//自动编译
npm install electron-rebuild --save-dev
npx electron-rebuild
先自动编译,失败再尝试手动
踩了不少坑,此时输入require(‘robotjs’)会报错
Uncaught Error: The module '\\?\D:\newutkal\node_modules\@serialport\bindings\build\Release\bindings.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION 72. This version of Node.js requires
NODE_MODULE_VERSION 80. Please try re-compiling or re-installing
the module (for instance, using `npm rebuild` or `npm install`).
//在main.js加一行
app.allowRendererProcessReuse = false
//这样就可以了
这是electron开发经常用到的一个技巧
第一步最重要的是监听键鼠和鼠标事件,这是js常用命令了
//创建robot.js(https://robotjs.io/docs/syntax#keytapkey-modifier)
const {ipcMain} = require('electron')
const robot = require('robotjs')
const vkey = require('vkey')
function handleMouse(data) {
//假设data里来的数据是{X,Y,screen:{width,height},video:{width,height}}
const {X,Y,screen,video} = data
let realX=X*screen.width/video.width
let realY=Y*screen.height/video.height
robot.moveMouse(realX,realY)
robot.mouseClick()//点击
}
function handleKey(data){
//data{keyCode,alt,ctrl,shift}
const {keyCode,alt,ctrl,shift} = data
const modifiers=[]
if(data.shift) modifiers.push('shift')
if(data.alt) modifiers.push('alt')
if(data.shift) modifiers.push('shift')
if(data.ctrl) modifiers.push('ctrl')
let key = vkey[data.keyCode].toLowerCase()
if(key[0]!=='<'){
robot.keyTap(key,modifiers)
}
}
module.exports = function(){
//根据接收的指令调用robotjs
ipcMain.on('robot',(e,type,data)=>{
// console.log('hadone')
if(type==='mouse'){
handleMouse(data) //处理鼠标事件
}else if(type==='key'){
handleKey(data) //处理键盘事件
}
})
}
app.on里引入执行
require('./robot.js')()
渲染进程监听 peer-control.js,并发送给主进程
peer.on('robot',(type,data)=>{
console.log(type,data)
if(type==='mouse'){
data.screen = {
width:window.screen.width,
height:window.screen.height,
}
}
ipcRenderer.send('robot',type,data)
})
//控制页面windows监听事件 app.ts
//监听键盘输入
window.onkeydown = function(e){
console.log('键盘点击',e)
//data{keyCode,alt,ctrl,shift}
let data={}
data = {
keyCode:e.keyCode,
shift:e.shiftKey,
control:e.ctrlKey,
alt:e.altKey
}
peer.emit('robot','key',data)
}
//监听鼠标输入
window.onmouseup = function(e){
console.log('鼠标点击')
//假设data里来的数据是{X,Y,screen:{width,height},video:{width,height}}
let data={}
data = {
X:e.clientX,
Y:e.clientY,
video:{
width:video.getBoundingClientRect().width,
height:video.getBoundingClientRect().height,
}
}
peer.emit('robot','mouse',data)
}
至此,完成了基础的鼠标键盘事件