Is it possible to detect if Magic Mouse/Trackpad is being touched?

心不动则不痛 提交于 2019-12-10 10:25:16

问题


Just wondering if there is a way to receive a callback in Cocoa if Magic Mouse or Trackpad is being touched by the user?

I looked into Quartz Events, but it seems I can only get callbacks if the mouse is moving or clicked etc.

Note that I want to receive a callback even if my app is not active. It's a background utility app. Also, it can't use private frameworks as it's going to be a Mac App Store app.


回答1:


You could use this code to trap the events: (create a new Cocoa application and put this in the application delegate)

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);
}

but.. sandboxing will probably prevent you from using CGEventTapCreate because by nature, it allows an application to listen to the whole event system, which is not very secure. If not using the sandboxing is acceptable to you, then eventTapCallback is called when a new touch is made on the touchpad.



来源:https://stackoverflow.com/questions/9833522/is-it-possible-to-detect-if-magic-mouse-trackpad-is-being-touched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!