Is Magic Mouse / Trackpad Touch Detection Possible?
Just wondering if there is a way to get a callback in Cocoa if the user touches the Magic Mouse or Trackpad?
I looked at the Quartz events, but it seems I can only receive callbacks if the mouse is moved or clicks, etc.
Please note that I want to receive a callback even though my application is inactive. It is a background utility. Also, it cannot use private frameworks as it will be a Mac App Store app.
source to share
You can use this code to capture events: (create a new Cocoa app and put it in the app delegate)
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
initCGEventTap();
}
NSEventMask eventMask = NSEventMaskGesture|NSEventMaskMagnify|NSEventMaskSwipe|NSEventMaskRotate|NSEventMaskBeginGesture|NSEventMaskEndGesture;
CGEventRef eventTapCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef eventRef, void *refcon) {
// convert the CGEventRef to an NSEvent
NSEvent *event = [NSEvent eventWithCGEvent:eventRef];
// filter out events which do not match the mask
if (!(eventMask & NSEventMaskFromType([event type]))) { return [event CGEvent]; }
// do stuff
NSLog(@"eventTapCallback: [event type] = %ld", [event type]);
// return the CGEventRef
return [event CGEvent];
}
void initCGEventTap() {
CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionListenOnly, kCGEventMaskForAllEvents, eventTapCallback, nil);
CFRunLoopAddSource(CFRunLoopGetCurrent(), CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0), kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
}
but .. the sandbox probably won't let you use CGEventTapCreate
, as by its nature it allows the application to listen to the entire event system, which is not very secure. If you are not using sandboxing, it comes in handy eventTapCallback
when a new touch is made on the touchpad.
source to share