NSView cannot grab Ctrl+Tab Keydown event

669 views Asked by At

In my Mac App, I listen to key press events and pass them on to the internal client, depending on modifiers and key code.

Currently, I'm facing the problem, that I can't get a hold of the "Ctrl+Tab" event. It seems that the "App" itself tries to handle this, which makes sense for tab based applications. So I disabled the Tabbingmode, but still, the Ctrl+Tab never fires the KeyDown event. Any other combination of key code and modifier seems to pass just fine.

Any suggestions on how to get the key down event fired for Ctrl+Tab?

2

There are 2 answers

4
Charles Srstka On BEST ANSWER

In my testing, NSView's -keyDown: method does not seem to get called on NSView subclasses for control-tab key events. However, you can intercept them at the application level with an NSApplication subclass:

@interface MyApplication: NSApplication
@end

@implementation MyApplication

- (void)sendEvent:(NSEvent *)event {
    if (event.type == NSEventTypeKeyDown &&
        [event.charactersIgnoringModifiers isEqualToString:@"\t"] &&
        (event.modifierFlags & NSEventModifierFlagDeviceIndependentFlagsMask) == NSEventModifierFlagControl) {
        NSLog(@"ctrl-tab");
    }

    [super sendEvent:event];
}

@end
0
arts On

Use

override func viewDidLoad() {
    super.viewDidLoad()

    NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
        if self.myKeyDown(with: $0) {
            return nil
        } else {
            return $0
        }
    }
}

and

func myKeyDown(with event: NSEvent) -> Bool {
    // handle keyDown only if current window has focus, i.e. is keyWindow
    guard let locWindow = self.view.window,
          NSApplication.shared.keyWindow === locWindow else {
        return false
    }

    switch event.specialKey {

    case NSEvent.SpecialKey.tab:
        // your event for tab action
        return true
    default:
        break
    }
    return false
}

if you need shortcut keys

func myKeyDown(with event: NSEvent) -> Bool {
    // handle keyDown only if current window has focus, i.e. is keyWindow
    guard let locWindow = self.view.window,
          NSApplication.shared.keyWindow === locWindow else {
        return false
    }

    switch event.specialKey {
    case NSEvent.SpecialKey.tab:
        // your code for tab action
        return true
    default:
        break
    }

    switch event.modifierFlags.intersection(.deviceIndependentFlagsMask) {
    case [.command]:
        switch event.charactersIgnoringModifiers! {
        case "w":
            // your code for cmd+w action (example)
            break
        default:
            break
        }
    }
    return false
}