Cocoa Listen to Keyboard command+up Event
Asked Answered
T

1

7

I am working on a macOS app and I would like to handle a local hotkey event (command + up arrow key) in a NSViewController.

Here's how I do it with Swift:

override func keyDown(with event: NSEvent) {

    let modifierkeys = event.modifierFlags.intersection(.deviceIndependentFlagsMask);
    let hasCommand = modifierkeys == .command;

    switch Int(event.keyCode) {
    case kVK_UpArrow where hasCommand:
        print("command up");
        break;
    case kVK_ANSI_B where hasCommand:
        print("command B");
        break;
    default:
        break;
    }
}

When I build and press command+up in the view, the console shows nothing. But when I press command+B, "command B" is logged out.

So why isn't this working for Command+up? How should I achieve this?

Trapeziform answered 6/4, 2017 at 12:7 Comment(0)
T
5

I've found the solution:

self.keyMonitor = NSEvent.addLocalMonitorForEvents(matching: NSEventMask.keyDown, handler: { (event) -> NSEvent? in

    if (event.modifierFlags.contains(.command)){
        if (Int(event.keyCode) == kVK_UpArrow){
            print("command up");
            return nil;
        }
    }

    return event;

});

The key point is to interrupt the keydown event and prevent it from being dispatched by returning nil

Trapeziform answered 6/4, 2017 at 12:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.