是否可以检测是否正在触摸Magic Mouse / Trackpad? [英] Is it possible to detect if Magic Mouse/Trackpad is being touched?

查看:177
本文介绍了是否可以检测是否正在触摸Magic Mouse / Trackpad?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道如果有可能在Cocoa中接收一个回调,如果用户触摸了Magic Mouse或者Trackpad?

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

我看过Quartz活动,它似乎只能得到回调,如果鼠标移动或点击等。

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

注意,即使我的应用程序不活动,我想接收回调。它是一个后台实用程序。此外,它不能使用私有框架,因为它将是一个Mac App Store应用程序。

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.

推荐答案

捕获事件:(创建一个新的Cocoa应用程序并将其放在应用程序委托中)

You could use this code to trap the events: (create a new Cocoa application and put this in the application 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);

}

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

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.

这篇关于是否可以检测是否正在触摸Magic Mouse / Trackpad?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆