You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:15:34