后台的应用程序不会对关键事件采取行动。您有两个选项可以让您的应用在后台处理它们:Event Taps和+[NSEvent addLocalMonitorForEventsMatchingMask:]
. 该NSEvent
选项非常简单:
// A block callback to handle the events
NSEvent * (^monitorHandler)(NSEvent *);
monitorHandler = ^NSEvent * (NSEvent * theEvent){
NSLog(@"Got a keyDown: %d", [theEvent keyCode]);
// The block can return the same event, a different
// event, or nil, depending on how you want it to be
// handled later. In this case, being in the background,
// there won't be any handling regardless.
return theEvent;
};
// Creates an object that we don't own but must keep track of to
// remove later (see docs). Here, it is placed in an ivar.
monitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask
handler:monitorHandler];
但是您已经在玩弄事件水龙头了,所以您可能只想走那条路。
// Creates an object that must be CFRelease'd when we're done
CFMachPortRef tap = CGEventTapCreateForPSN(myOwnPSN,
kCGTailAppendEventTap,
kCGEventTapOptionDefault,
kCGEventKeyDown,
myEventTapCallback,
NULL);
回调很简单。有关信息,请参阅事件服务参考中的回调。