beakr
beakr

Reputation: 5857

How to detect a combination of keys pressed in a Mac app?

I know that keyboard events in Mac apps can be triggered like so:

- (void) keyDown(NSEvent*)event {
    switch ([event keyCode]) {
        case someKeyCode:
            NSLog(@"blah blah blah");

        default:
            break;
    }
}

But how would I make my app react to a combination of key pressed, such as the Konami Code?

Thanks!

Upvotes: 0

Views: 793

Answers (1)

The Lazy Coder
The Lazy Coder

Reputation: 11818

you will need to build a history list that keeps track of the keys that were pressed over the past however long. and when the list of keys contains a match for your "Code" whether it be the konami code or otherwise. Your match triggers another event and clears the key history.

add the data to an array via strings for control keys

static NSMutableArray *array = [NSMutableArray array];
[array addObject:@"[UP]"]; // etc for each key you would have a special key

then you can test like this

if ([[array componentsJoinedByString:@""] isEqualToString:@"[UP][UP][DOWN][DOWN]"]){
    array = [NSMutableArray array];
    [self commandfound]
}

hope that helps

Upvotes: 2

Related Questions