【发布时间】:2020-02-05 16:07:03
【问题描述】:
我正在尝试使用CGEvent.tapCreate(tap:place:options:eventsOfInterest:callback:userInfo:) 方法拦截鼠标移动事件,如下所示:
let cfMachPort = CGEvent.tapCreate(tap: CGEventTapLocation.cghidEventTap,
place: CGEventTapPlacement.headInsertEventTap,
options: CGEventTapOptions.defaultTap,
eventsOfInterest:CGEventMask(CGEventType.mouseMoved.rawValue),
callback: {(eventTapProxy, eventType, event, mutablePointer) -> Unmanaged<CGEvent>? in event
print(event.type.rawValue) //Breakpoint
return nil
}, userInfo: nil)
let runloopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, cfMachPort!, 0)
let runLoop = RunLoop.current
let cfRunLoop = runLoop.getCFRunLoop()
CFRunLoopAddSource(cfRunLoop, runloopSource, CFRunLoopMode.defaultMode)
我作为事件类型 eventsOfInterest mouseMoved 事件传递,原始值为 5 as seen in the documentation。但由于某种原因,除非我用鼠标单击,否则我的 print() 不会执行。在调试器中检查发送鼠标事件给我一个原始值 2,根据the documentation 是leftMouseUp 事件。
在documentation for CGEvent.tapCreate(tap:place:options:eventsOfInterest:callback:userInfo:) 中写着:
事件点击接收按键向上和按键向下事件 [...]
所以看起来该方法通常忽略mouseMoved 事件?!但是我应该如何收听mouseMoved 事件呢?我试图阻止我的光标(自定义光标)被替换(例如,当我将鼠标悬停在屏幕底部的应用程序坞上时)。
【问题讨论】:
-
不,很遗憾没有。除了上述 API 描述了一个遗留 API 之外,我还需要捕获应用程序范围之外的事件。所以我需要一个更底层的方法来捕捉鼠标事件。
-
您在哪个版本的 macOS 上测试?你的应用是沙盒的吗?无论哪种方式,您的应用都可能需要被授予用户控制 UI 的权限。
-
@KenThomases 我在 10.15.2 上进行测试,并且该应用程序没有被沙盒化。我给予了可访问性和屏幕录制津贴。
-
@KenThomases 给出的代码示例实际上只会在未授予访问权限时崩溃;因为
cfMachPort将为零 -
@TheNextman 我在 Swift 上找不到任何名为
CGEventMaskBit的东西。我正在使用CGEventMask(CGEventType.mouseMoved.rawValue)来获取 UInt64。根据文档,这是正确的。我也找不到像kCGEventMaskForAllEvents这样的kCGEventMask*。 developer.apple.com/documentation/coregraphics/cgeventmask
标签: swift macos core-graphics