centree
centree

Reputation: 2439

Command-Key-Up Cocoa

I'm trying to mimic the functionality of the cmd-tab keyboard shortcut where the user can switch between applications hitting a certain key and then when they release command something happens.

I'm using this code right now but it can only detects keydown. I need this to fire on key up

- (void)flagsChanged:(NSEvent *)theEvent {

if ([theEvent modifierFlags] & NSCommandKeyMask) {
    NSLog(@"Do my stuff here");
}
}

Thanks

Upvotes: 4

Views: 2002

Answers (1)

ipmcc
ipmcc

Reputation: 29886

According to the docs:

Informs the receiver that the user has pressed or released a modifier key (Shift, Control, and so on).

What you need to do here is when you get the event in which the command key goes down, you need to set a flag somewhere, and in subsequent calls, check for the absence of the command key being down.

For instance, assuming you have an ivar called _cmdKeyDown:

- (void)flagsChanged:(NSEvent *)theEvent
{
    [super flagsChanged:theEvent];

    NSUInteger f = [theEvent modifierFlags];
    BOOL isDown = !!(f & NSCommandKeyMask);
    if (isDown != _cmdKeyDown)
    {
        NSLog(@"State changed. Cmd Key is: %@", isDown ? @"Down" : @"Up");
        _cmdKeyDown = isDown;
    }
}

Upvotes: 9

Related Questions