I'm trying to create an OS X keyboard hook for assistive technology purposes (i.e. don't worry, not a keylogger).
When a user presses a key, I want to prevent the real keypress and send a fake keypress (character of my choosing) instead.
I have the following code:
- (void) hookTheKeyboard {
CGEventMask keyboardMask = CGEventMaskBit(kCGEventKeyDown);
id eventHandler = [NSEvent addGlobalMonitorForEventsMatchingMask:keyboardMask handler:^(NSEvent *keyboardEvent) {
NSLog(@"keyDown: %c", [[keyboardEvent characters] characterAtIndex:0]);
//Want to: Stop the keyboard input
//Want to: Send another key input instead
}];
}
Any help accomplishing either of those goals? Basically modifying the NSEvent "keyboardEvent" to send a different character. Thanks.
I happened across this answer, needing to do the same but only for events within my own application not global . There is a much simpler solution, for this much simpler problem, which I am noting here incase it's useful for anyone else:
This seems to work perfectly for me and I didn't have to even modify the keyCode part - but maybe this could be an issue...
Example in Swift:
}
You can't do this with the
NSEvent
API, but you can do this with aCGEventTap
. You can create an active event tap and register a callback that receives aCGEventRef
and can modify it (if necessary) and return it to modify the actual event stream.EDIT
Here's a simple program that, while running, replaces every "b" keystroke with a "v":
(Funny story: as I was editing this post, I kept on trying to write "replaces every 'b' keystroke", but it kept on coming out as "replaces every 'v' keystroke". I was confused. Then I remembered that I hadn't stopped the app yet.)