昨晚玩一个模拟经营的游戏,由于升级太慢我就不停的种树卖树来换取经验值。不过重复点击10几分钟后,实在受不了。网上本来准备找个鼠标自动点击的软件用用。结果没找到趁手的。如是自己写了个。
自己设置需要点击的一组动作,长按(100,200),点击(576,789),点击(750,550)。类似在对应坐标点操作鼠标。
原理非常简单,我就不贴代码了,主要说下如何控制鼠标点击事件。
注册系统辅助权限,这里会触发用户授权
let@H_301_11@ opts = NSDictionary(object@H_301_11@: kcfBooleanTrue,forKey: kAXTrustedCheckOptionPrompt.takeUnretainedValue() as@H_301_11@ NSString
) as@H_301_11@ CFDictionary
guard AXIsProcessTrustedWithOptions(opts) == true@H_301_11@ else@H_301_11@ { return@H_301_11@ }
鼠标事件
// 鼠标左键按下
let mouseDown = CGEvent(mouseEventSource: nil,mouseType: .leftMouseDown@H_301_11@,mouseCursorPosition: CGPoint(x@H_301_11@: 200@H_301_11@,y@H_301_11@: 300@H_301_11@),mouseButton: .left@H_301_11@
)
mouseDown?.post@H_301_11@(tap: .cghidEventTap@H_301_11@)
// 鼠标左键抬起
let mouseUp = CGEvent(mouseEventSource: nil,mouseType: .leftMouseUp@H_301_11@,mouseButton: .left@H_301_11@
)
mouseUp?.post@H_301_11@(tap: .cghidEventTap@H_301_11@)
以上两个事件,组成了一个鼠标左键在坐标(200,300)点击事件
MouseType支持类型
/* Constants that specify the different types of input events. */@H_301_11@
public@H_301_11@ enum@H_301_11@ CGEventType : UInt32 {
/* The null event. */@H_301_11@
case@H_301_11@ null@H_301_11@
/* Mouse events. */@H_301_11@
case@H_301_11@ leftMouseDown
case@H_301_11@ leftMouseUp
case@H_301_11@ rightMouseDown
case@H_301_11@ rightMouseUp
case@H_301_11@ mouseMoved
case@H_301_11@ leftMouseDragged
case@H_301_11@ rightMouseDragged
/* Keyboard events. */@H_301_11@
case@H_301_11@ keyDown
case@H_301_11@ keyUp
case@H_301_11@ flagsChanged
/* Specialized control devices. */@H_301_11@
case@H_301_11@ scrollWheel
case@H_301_11@ tabletPointer
case@H_301_11@ tabletProximity
case@H_301_11@ otherMouseDown
case@H_301_11@ otherMouseUp
case@H_301_11@ otherMouseDragged
/* Out of band event types. These are delivered to the event tap callback to notify it of unusual conditions that disable the event tap. */@H_301_11@
case@H_301_11@ tapDisabledByTimeout
case@H_301_11@ tapDisabledByUserInput
}
长按事件
有人可能会留意到上述没有长按事件
长按事件就是 .leftMouseDown,达到你需要长按的时间后,再触发.leftMouseUp
扩展
一般情况你做好一系列点击组合后,是用快捷键触发开始的。那么MacOS中如何监听系统快捷键呢或者键盘事件?
NSEvent.addGlobalMonitorForEvents(matching: .keyDown,handler: {
[unowned self] event@H_301_11@ in@H_301_11@
// num1:18,num2:19@H_301_11@
if@H_301_11@ event@H_301_11@.keyCode == 18@H_301_11@ {
// self.startAction()@H_301_11@
}
})