Swift macOS MenuBarExtra中CGEventTap拦截mouseMoved事件失效求助
问题:CGEventTap返回nil无法拦截mouseMoved事件?
我正在开发一款仅运行在macOS MenuBarExtra中、无主界面的应用,目的是限制鼠标光标进入屏幕特定区域。
我用Swift创建了CGEventTap来监听mouseMoved事件:
let eventMask = (1 << CGEventType.mouseMoved.rawValue); currentTap = CGEvent.tapCreate( tap: .cghidEventTap, place: .headInsertEventTap, options: .defaultTap, eventsOfInterest: CGEventMask(eventMask), callback: cgEventCallback, userInfo: nil ); let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, currentTap, 0) CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes)
根据Apple的CGEventTapCallback文档,在回调中返回nil应该会删除事件:
func cgEventCallback(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent, refcon: UnsafeMutableRawPointer?) -> Unmanaged<CGEvent>? { return nil; }
后续我会添加逻辑,但目前针对mouseMoved事件返回nil并未删除该事件。我是Swift和Apple生态编程新手,可能忽略了某些细节,请问问题出在哪里?
完整示例代码:
func cgEventCallback(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent, refcon: UnsafeMutableRawPointer?) -> Unmanaged<CGEvent>? { return nil; } @main struct PlaygroundApp: App { @State var currentNumber: String = "0" @State var currentTap: CFMachPort? = nil; var body: some Scene { MenuBarExtra(currentNumber, systemImage: "\(currentNumber).square") { Button("Test Event") { let eventMask = (1 << CGEventType.mouseMoved.rawValue) | (1 << CGEventType.keyDown.rawValue) | (1 << CGEventType.keyUp.rawValue); currentTap = CGEvent.tapCreate( tap: .cghidEventTap, place: .headInsertEventTap, options: .defaultTap, eventsOfInterest: CGEventMask(eventMask), callback: cgEventCallback, userInfo: nil ); let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, currentTap, 0) CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes) currentNumber = "1"; } } } }
内容的提问来源于stack exchange,提问作者Daedalus
相关产品推荐
相关产品推荐

