Pergunta

I'm trying to detect whether the command key is pressed, and for the life of me cannot figure out what is wrong with the following. I've overridden a view to provide the code below:

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

    NSLog(@"flags changed in %@", self);
    BOOL commandKeyPressed = ([theEvent modifierFlags] & NSCommandKeyMask);

    if (commandKeyPressed)
        NSLog(@"command key in %@", self);
}

I see the "flags changed" message whenever I press the command key, but not the "command key in" message. What am I missing?

Foi útil?

Solução

A BOOL is a signed char, so when you convert an int to a BOOL, you lop off all but the low 8 bits. And in your case, the nonzero bit is not in the low 8 bits. Instead, say

BOOL commandKeyPressed = ([theEvent modifierFlags] & NSCommandKeyMask) != 0;

or just

if ([theEvent modifierFlags] & NSCommandKeyMask)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top