5

Ok, I understand how to determine from an NSEvent if a modifierkey is pressed :

if ([theEvent modifierFlags] & NSAlternateKeyMask) {
        // The Option/Alt key was pressed
    }

But this also captures the optionkey and another modifierkey at the same time, eg Option+Shift, or any combination with the optionkey.

How do I test for only the optionkey and nothing else?

koen
  • 5,383
  • 7
  • 50
  • 89

2 Answers2

4

Like this:

const NSUInteger kNotAlt = NSAlphaShiftKeyMask | NSShiftKeyMask | NSControlKeyMask | NSCommandKeyMask;
NSUInteger modFlags = [theEvent modifierFlags];
if (((modFlags & NSAlternateKeyMask) != 0) &&
    ((modFlags & kNotAlt) == 0))
{
    // Only alt was pressed
}
user1118321
  • 25,567
  • 4
  • 55
  • 86
4

You can also try

NSUInteger modFlags = [theEvent modifierFlags];
if ((modFlags & NSCommandKeyMask) && !(modFlags & ~NSCommandKeyMask))
{
    // Only alt was pressed
}
Tony
  • 36,591
  • 10
  • 48
  • 83
  • 1
    Thanks everyone. In the meantime I also found another, more general solution. I hope the formatting is ok.
    `NSUInteger modifiers = [event modifierFlags] & (NSCommandKeyMask | NSAlternateKeyMask | NSShiftKeyMask | NSControlKeyMask);
    if (modifiers == NSAlternateKeyMask)
    {
    // only alt was pressed
    }`
    – koen Feb 05 '12 at 03:07