【问题标题】:Simulating human mouse movement模拟人类鼠标移动
【发布时间】:2015-09-21 15:16:13
【问题描述】:

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

【问题讨论】:

    标签: macos swift cocoa


    【解决方案1】:

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

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

    【讨论】:

    • 我不知道如何使用 CoreAnimation 来操作鼠标,您能再解释一下吗?
    • 也许我误解了 - 你想以编程方式移动实际的鼠标光标吗?还是您要移动其他东西?
    • 是的,我想移动实际的鼠标光标。但据我所知,这不是核心动画可以做的事情吗?
    • 是的 - 道歉 - 我认为核心动画只能动画视图
    猜你喜欢
    • 1970-01-01
    • 2016-04-14
    • 2015-10-15
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多