简体   繁体   English

在macOS(swift或objc)上模拟鼠标滚轮

[英]Simulate mouse wheel on macOS (swift or objc)

I'm using the following code to simulate mouse click event 我正在使用以下代码来模拟鼠标单击事件

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)
}

What is similar way to simulate mouse wheel scroll events? 有什么类似的模拟鼠标滚轮滚动事件的方式?

Thanks to Willeke new event constructor was added starting from 10.13. 感谢Willeke,从10.13开始添加了新的事件构造函数。

Here is the my solution but it works only for macOS version >= 10.13 这是我的解决方案,但仅适用于版本大于等于10.13的macOS

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM