3

I am looking to intercept keyboard events in a Mac app.

I would like the user to initiate a "record" activity which will copy the keystones and then a "stop" activity.

Is that possible via Cocoa's Mac API?

darksky
  • 20,411
  • 61
  • 165
  • 254

2 Answers2

6

Have a look at the NSEvent method addLocalMonitorForEventsMatchingMask:handler:. This will allow you to receive events (specifically keyDown events in your case) that occur in your app, and you can then do whatever you want with the keystrokes that the method returns. Here is a simple example of how to use that method:

self.keystrokes = [NSMutableString string];
    [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^NSEvent* (NSEvent* event){
        NSString *keyPressed = event.charactersIgnoringModifiers;
        [self.keystrokes appendString:keyPressed];
        return event;
    }];
rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • Of course you cannot intercept other apps key strokes, can you? – darksky Jun 05 '12 at 01:54
  • I believe you can, but with a global monitor rather than the local one (also an NSEvent method). – rdelmar Jun 05 '12 at 01:55
  • 2
    The big problem with using the NSEvent API for global monitoring is that there are certain kinds of events you don't get. (And the list is slightly different depending on OS version.) So if you have to, e.g., record global hotkeys in Lion, they just won't show up. If you care about any of those cases, you have no choice but to drop down to the CGEventTap level (from the other answer). – abarnert Jun 05 '12 at 18:47
3

To intercept all keyboard input (and also mouse if you want it) check out the Quartz Events API. This post has some code demonstrating usage of the API.

Community
  • 1
  • 1
Wilbur Vandrsmith
  • 5,040
  • 31
  • 32