模拟人体鼠标移动

时间:2015-09-21 15:16:13

标签: macos swift cocoa

您好我正在尝试创建一个程序,通过一个平滑的随机运动将光标从给定点移动到另一个点。我目前使用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
}

1 个答案:

答案 0 :(得分:0)

我真的建议将Core Animation用于这样的事情,这将为您节省大量的时间和精力。

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