【问题标题】:Is it possible to detect if Magic Mouse/Trackpad is being touched?是否可以检测是否正在触摸 Magic Mouse/Trackpad?
【发布时间】:2012-03-23 02:49:46
【问题描述】:

只是想知道如果用户触摸了 Magic Mouse 或 Trackpad,是否有办法在 Cocoa 中接收回调?

我查看了 Quartz 事件,但似乎只有在鼠标移动或点击等情况下才能获得回调。

请注意,即使我的应用程序未处于活动状态,我也希望收到回调。这是一个后台实用程序。此外,它不能使用私有框架,因为它将成为 Mac App Store 应用程序。

【问题讨论】:

    标签: macos cocoa mouseevent quartz-graphics


    【解决方案1】:

    您可以使用此代码来捕获事件:(创建一个新的 Cocoa 应用程序并将其放入应用程序委托中)

    NSEventMask eventMask = NSEventMaskGesture | NSEventMaskMagnify | NSEventMaskSwipe | NSEventMaskRotate | NSEventMaskBeginGesture | NSEventMaskEndGesture;
    
    CGEventRef eventTapCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef eventRef, void *userInfo) {
        NSEvent *event = [NSEvent eventWithCGEvent:eventRef];
    
        // only act for events which do match the mask
        if (eventMask & NSEventMaskFromType([event type])) {
            NSLog(@"eventTapCallback: [event type] = %ld", [event type]);
        }
    
        return [event CGEvent];
    }
    
    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionListenOnly, kCGEventMaskForAllEvents, eventTapCallback, nil);
        CFRunLoopAddSource(CFRunLoopGetCurrent(), CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0), kCFRunLoopCommonModes);
        CGEventTapEnable(eventTap, true);
    }
    

    但是.. 沙盒可能会阻止您使用CGEventTapCreate,因为本质上,它允许应用程序监听整个事件系统,这不是很安全。如果您可以接受不使用沙盒,则在触摸板上进行新触摸时调用eventTapCallback

    【讨论】:

    • 沙盒应用程序也可以这样做,它们需要在系统偏好设置中添加(在安全/隐私下)允许辅助功能访问。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2018-10-26
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    相关资源
    最近更新 更多