Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 810
centree Avatar asked Jan 14 '23 04:01

centree


1 Answers

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;
    }
}
like image 176
ipmcc Avatar answered Feb 01 '23 14:02

ipmcc