gpt4 book ai didi

macos - 模拟人类鼠标移动

转载 作者:行者123 更新时间:2023-11-28 08:57:34 25 4
gpt4 key购买 nike

您好,我目前正在尝试创建一个程序,以一种平滑的随机运动将光标从一个给定点移动到另一个点。我目前使用 CoreGraphics 创建了以下内容,它可以工作,但鼠标移动变得非常不稳定。有想法该怎么解决这个吗?非常感激。我在 applicationDidFinishLaunching 中的 Mac OS X 应用程序开始时调用以下代码:

var pos = NSEvent.mouseLocation()
pos.y = NSScreen.mainScreen()!.frame.height - pos.y
moveMouse(CGPoint(x:200,y:200), from: pos)

这些是我创建的函数:

func transMouse(point:CGPoint) {
let move = CGEventCreateMouseEvent(nil, CGEventType.MouseMoved, point, CGMouseButton.Left)
CGEventPost(CGEventTapLocation.CGHIDEventTap, move)
}

func moveMouseOne(direction:Character, _ currentPos:CGPoint) -> CGPoint {
var newPos = currentPos

if direction == "r" {
newPos.x = currentPos.x + 1
} else if direction == "l" {
newPos.x = currentPos.x - 1
} else if direction == "u" {
newPos.y = currentPos.y - 1
} else if direction == "d" {
newPos.y = currentPos.y + 1
}
transMouse(newPos)

return newPos
}

func moveMouse(to:CGPoint, from:CGPoint) -> CGPoint {

let dx:Int = Int(to.x - from.x)
let dy:Int = Int(to.y - from.y)

var moves = Array<Character>()

if dx > 0 {
for _ in 0..<dx {
moves.append("r")
}
} else {
for _ in 0..<(-dx) {
moves.append("l")
}
}

if dy > 0 {
for _ in 0..<dy {
moves.append("d")
}
} else {
for _ in 0..<(-dy) {
moves.append("u")
}
}
var pos = from
let delay:Double = 0.0008
let startTime = DISPATCH_TIME_NOW
for var i = 0; i < moves.count; ++i {
let time = dispatch_time(startTime, Int64(delay * Double(i) * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {
let count = moves.count
let random = Int(arc4random_uniform(UInt32(count)))
pos = self.moveMouseOne(moves[random], pos)
if random == count - 1 {
moves.popLast()
} else {
moves[random] = moves.popLast()!
}
}
}

return to
}

最佳答案

我真的推荐使用 Core Animation 做这样的事情,会节省你很多时间和精力。

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreAnimation_guide/Introduction/Introduction.html

关于macos - 模拟人类鼠标移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32698782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com