Имитация колеса мыши в macOS (swift или objc)

Я использую следующий код для имитации события щелчка мыши

public class func leftMouseDown(onPoint point: CGPoint) {

    guard let downEvent = CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left) else {
        return
    }

    downEvent.setIntegerValueField(CGEventField.eventSourceUserData, value: 1)

    downEvent.post(tap: CGEventTapLocation.cghidEventTap)
}

public class func leftMouseUp(onPoint point: CGPoint) {

    guard let upEvent = CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left) else {
        return
    }

    upEvent.setIntegerValueField(CGEventField.eventSourceUserData, value: 1)

    upEvent.post(tap: CGEventTapLocation.cghidEventTap)
}

Как можно имитировать события прокрутки колеса мыши?


person Ivan Makhnyk    schedule 25.07.2018    source источник
comment
Вы проверили документацию CGEvent?   -  person Willeke    schedule 25.07.2018


Ответы (1)


Благодаря Willeke был добавлен новый конструктор событий, начиная с 10.13.

Вот мое решение, но оно работает только для версии macOS >= 10.13.

public class func scrollMouse(onPoint point: CGPoint, xLines: Int, yLines: Int) {
    if #available(OSX 10.13, *) {
        guard let scrollEvent = CGEvent(scrollWheelEvent2Source: nil, units: CGScrollEventUnit.line, wheelCount: 2, wheel1: Int32(yLines), wheel2: Int32(xLines), wheel3: 0) else {
            return
        }
        scrollEvent.setIntegerValueField(CGEventField.eventSourceUserData, value: 1)
        scrollEvent.post(tap: CGEventTapLocation.cghidEventTap)
    } else {
        // scroll event is not supported for macOS older than 10.13
    }
}
person Ivan Makhnyk    schedule 26.07.2018