Is it possible to detect if Magic Mouse/Trackpad i

2019-05-14 11:10发布

问题:

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.