我希望我的应用程序在发生某个键盘事件时收到通知(例如,在不到 0.5 秒的时间内按下 alt 键两次)。该应用程序不应该是前端应用程序。我怎样才能做到这一点 ?
问问题
265 次
1 回答
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;
}
于 2012-11-19T17:56:13.433 回答