darksky
darksky

Reputation: 21019

Accessing Keyboard API

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?

Upvotes: 3

Views: 2083

Answers (2)

rdelmar
rdelmar

Reputation: 104082

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;
    }];

Upvotes: 6

Wilbur Vandrsmith
Wilbur Vandrsmith

Reputation: 5050

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.

Upvotes: 3

Related Questions