Question

I have a few checkboxes along with textfields on a NSPanel that opens to get user parameters. As an option, I'd like the user to be able to set/unset all the checkboxes on the panel by holding the option key when they press any of the checkboxes.

I'm not sure where/how to check what the key board is doing when the user clicks the button.

Was it helpful?

Solution

check [NSEvent modifierFlags]...

if ([NSEvent modifierFlags ] & NSAlternateKeyMask)
{
    //do something
}

OTHER TIPS

Just my 2c, a Swift 3 version:

if NSEvent.modifierFlags().contains(NSEventModifierFlags.command) {
    print("Bingo")
}

One can see the rest of the flags in the documentation for NSEventModifierFlags.

Update: NSAlternateKeyMask is now deprecated. Use NSEventModifierFlagOption instead.

See NSEventModifierFlags for a complete overview about all modifier flags.

Swift 2.2:

if NSEvent.modifierFlags().contains(.AlternateKeyMask) {
    print("Option key pressed")
}

It's for someone who using swift and struggling with this.

if NSEvent.modifierFlags.rawValue & NSEvent.ModifierFlags.command.rawValue != 0 {
    // to do something.
}

Swift 4:

func optionKeyPressed() -> Bool
{        
    let optionKey = NSEvent.modifierFlags.contains(NSEvent.ModifierFlags.option)
    return optionKeyPressed
}

if optionKeyPressed()
{
    print ("option key pressed")
}

On macOS 10.14, when called from a NSGestureRecognizerDelegate method in ObjC, [NSEvent modifierFlags] was always returning 0 for me, regardless of what keys were down. I was able to reliably work around this by using [NSApp currentEvent] instead of NSEvent.

- (BOOL)isOptionKeyDown {
    NSEventModifierFlags keyEventFlags = [[NSApp currentEvent] modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask;
    return (keyEventFlags & NSEventModifierFlagOption) != 0;
}

Swift 5 - Also helps distinguish between the "up" and "down" presses of Option key

override func flagsChanged(with event: NSEvent) {
    print(event)
    
    if event.keyCode == 58 && event.modifierFlags.contains(NSEvent.ModifierFlags.option){
        print("Option Key is down!")
    }
    else if(event.keyCode == 58)
    {
        print("Option Key is up!")
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top