Capturing all multitouch trackpad input in Cocoa

后端 未结 2 1724
迷失自我
迷失自我 2020-12-25 08:07

Using touchesBeganWithEvent, touchesEndedWithEvent, etc you can get the touch data from the multitouch trackpad, but is there a way to block that touch data from moving the

2条回答
  •  囚心锁ツ
    2020-12-25 08:30

    As noted by valexa, using NSEventMask for CGEventTap is a hack. Tarmes also notes that Rob Keniger's answer no longer works (OS X >= 10.8). Luckily, Apple has provided a way to do this quite easily by using kCGEventMaskForAllEvents and converting the CGEventRef to an NSEvent within the callback:

    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] = %d", [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);
      CFRunLoopRun();
    }
    

    Note that the call to CFRunLoopRun() is included since this snippet was taken from a project which could not use NSApplication but instead had a bare-bones CFRunLoop. Omit it if you use NSApplication.

提交回复
热议问题