4

I am using flagsChanged in NSView to trigger events when a modifier key is pressed or released. However, I do not quite understand how to get the actual new state of the key when this happens, short of checking the state of each modifier key manually. I am currently using my own state array to check it, but this seems wrong and is not reliable. How do I do this correctly?

toastie
  • 1,934
  • 3
  • 22
  • 35

2 Answers2

7

Just check the event that gets passed into flagsChanged: against the various modifier key masks that you're interested in:

- (void)flagsChanged:(NSEvent *)theEvent {
   if (([theEvent modifierFlags] & NSAlternateKeyMask) == NSAlternateKeyMask) {
       // Do something based on the alt/option key being pressed
    } else if (([theEvent modifierFlags] & NSCommandKeyMask) == NSCommandKeyMask){
       // Do something based on the command key being pressed
    }
}
lottscarson
  • 578
  • 5
  • 14
  • Hm, but how do I know for example if it's the right or left alt that was pressed or released? – toastie Jan 16 '13 at 22:12
  • i.e. I hold down left alt, then press right alt up and down, (([theEvent modifierFlags] & NSAlternateKeyMask) == NSAlternateKeyMask) will stay true while left alt is held down – toastie Jan 16 '13 at 22:20
  • 1
    Ok, I found this, which seems to do the trick: http://stackoverflow.com/questions/10715910/is-there-a-way-to-differentiate-between-left-and-right-shift-keys-being-pressed Pretty dumb way of doing things I must say :) – toastie Jan 16 '13 at 22:25
  • You don't need the `== NSAlternateKeyMask` part – Alexander Jul 26 '14 at 22:05
0

I'm not sure what you mean by checking "manually". The flagsChanged: method gives you an NSEvent*, and you can pass that a modifierFlags message.

JWWalker
  • 22,385
  • 6
  • 55
  • 76