如果不是前端应用程序,如何将键盘事件发送到我的应用程序?

时间:2012-11-19 12:54:47

标签: macos cocoa

我希望我的应用程序在某个键盘事件发生时收到通知(例如,在不到0.5秒的时间内左手Alt键按下两次)。该应用程序不应该是前端应用程序。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

您需要安装事件点击以更改修改键。

这应该让你开始:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    CFMachPortRef eventTap;
    CGEventMask eventMask;
    CFRunLoopSourceRef runLoopSource;

    eventMask = CGEventMaskBit(kCGEventFlagsChanged);

    eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0,
                                eventMask, KeyHandler, NULL);
    if (!eventTap) {
        NSLog(@"failed to create event tap");
        exit(1);
    }

    runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);    
    CGEventTapEnable(eventTap, true);
}

static CGEventFlags previousFlags = 0;

CGEventRef KeyHandler(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
    if (type == kCGEventFlagsChanged) {
        CGEventFlags curAltkey = CGEventGetFlags(event)&kCGEventFlagMaskAlternate;
        if (curAltkey != previousFlags)
            NSLog(@"alt key changed");
    }

    return event;
}