gpt4 book ai didi

swift - MacOS Quartz Event Tap 监听错误事件

转载 作者:行者123 更新时间:2023-12-05 03:55:38 26 4
gpt4 key购买 nike

我正在尝试使用 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对于 CGEvent.tapCreate(tap:place:options:eventsOfInterest:callback:userInfo:) 它说:

事件点击接收按键弹起和按键按下事件 [...]

所以看起来该方法通常会忽略 mouseMoved 事件?!但是我应该如何监听 mouseMoved 事件呢?我试图防止我的光标(自定义光标)被替换(例如,当我将鼠标悬停在屏幕底部的应用程序停靠栏上时)。

最佳答案

您需要对 CGEventType 进行位移用于创建 CGEventMask 的值范围。在 Objective-C 中,有一个宏可以执行此操作:CGEventMaskBit .

来自CGEventMask文档:

to form the bit mask, use the CGEventMaskBit macro to convert each constant into an event mask and then OR the individual masks together

我不知道 swift 中的等效机制;但宏本身看起来像这样:

*/ #define CGEventMaskBit(eventType) ((CGEventMask)1 << (eventType))

在您的示例中,只需手动移动参数就足够了;例如

eventsOfInterest:CGEventMask(1 << CGEventType.mouseMoved.rawValue),

我要指出问题中给出的代码示例有点危险;因为它创建一个默认事件点击,然后删除事件而不是允许它们被处理。这搞乱了鼠标点击处理,并且使用鼠标实际终止应用程序很棘手。运行该示例的任何人都可以将事件点击类型设置为 CGEventTapOptions.listenOnly以防止这种情况。

关于swift - MacOS Quartz Event Tap 监听错误事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60079741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com