Reputation: 288
I've an application that needs disable some keys while the application in running (i.e: A, option, command, shift).
how can I do that?
the language or method used does not matter.
Upvotes: 0
Views: 227
Reputation: 35022
You can inspect, modify, and block keyboard events with a CGEventTap
.
The user will need to grant your app assistive privileges via the Security pane of System Preferences for events to be disabled before posting.
Something like this:
- (void)setKeyBlocker {
// You should filter this better than kCGEventMaskForAllEvents, depending on your needs.
CFMachPortRef eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, kCGEventMaskForAllEvents, cgEventCallback, NULL);
CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
CFRelease(eventTap);
CFRelease(runLoopSource);
}
CGEventRef callback(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *refcon) {
NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
if (event.type == kCGEventKeyDown) {
if ([event.characters isEqualToString:@"a"]) {
// Kill event
return NULL;
}
}
return cgEvent;
}
Upvotes: 1