【发布时间】:2017-03-15 14:53:34
【问题描述】:
我目前正在为 iOS 和 macOS 开发一个跨平台应用程序,它可以让您的 iOS 设备充当触控板。
使用CGDisplayMoveCursorToPoint,我可以在屏幕上移动光标。奇迹般有效。
使用“主机”应用程序中的这段代码(即在 macOS 上运行),我可以点击鼠标:
let currentPosition = foo() // call to my helper function
// that translates NSEvent.mouseLocation()
let downEvent = CGEvent(
mouseEventSource: nil,
mouseType: .leftMouseDown,
mouseCursorPosition: currentPosition,
mouseButton: .left
)
let upEvent = CGEvent(
mouseEventSource: nil,
mouseType: .leftMouseUp,
mouseCursorPosition: currentPosition,
mouseButton: .left
)
downEvent?.post(tap: CGEventTapLocation.cghidEventTap)
upEvent?.post(tap: CGEventTapLocation.cghidEventTap)
到目前为止,一切都很好。
现在我想在 iOS 设备上用两根手指实现滚动。问题不在于 iOS 和 macOS 之间的通信(顺便说一句,PeerTalk 很棒),而是我似乎无法在主机上触发滚动事件。
起初,我尝试过这样的事情:
let eventSource = CGEventSource(stateID: .hidSystemState)
let event = CGEvent(
mouseEventSource: eventSource,
mouseType: .scrollWheel,
mouseCursorPosition: currentPosition,
mouseButton: .left
)
不幸的是,event 始终是nil,我不知道为什么。我想尝试的另一种方法是(是的,我正在使用从全局事件侦听器获得的硬编码值,用于测试目的):
NSEvent.mouseEvent(
with: NSEventType.scrollWheel,
location: NSPoint(x: 671.0, y: 568.0),
modifierFlags: .init(rawValue: 0),
timestamp: 198223.19430632601,
windowNumber: 14389,
context: nil,
eventNumber: 0,
clickCount: 1,
pressure: 1.0
)
但是我的应用程序在创建事件时崩溃了:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: _NSEventMask64FromType(type) & (MouseMask|NSEventMaskMouseMoved)'
有没有人知道如何实现我的滚动功能?提前致谢!
【问题讨论】: