How to handle arrow key event in Cocoa app?

前端 未结 2 1699
不知归路
不知归路 2020-12-16 16:25

How to handle arrow key event in Cocoa app?

2条回答
  •  -上瘾入骨i
    2020-12-16 16:49

    In my case I wanted a presented NSViewController subclass to be able to listen to arrow key events for navigation with minimal effort. Here's the best solution I've found, a slight variation of Josh Caswell's answer.

    Define an event monitor (optional), can be locally in your NSViewController subclass .m

    id keyMonitor;
    

    Then start monitoring events, for example in viewDidLoad.

    keyMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *event) {
    
        unichar character = [[event characters] characterAtIndex:0];
        switch (character) {
            case NSUpArrowFunctionKey:
                NSLog(@"Up");
                break;
            case NSDownArrowFunctionKey:
                NSLog(@"Down");
                break;
            case NSLeftArrowFunctionKey:
                NSLog(@"Left");
                break;
            case NSRightArrowFunctionKey:
                NSLog(@"Right");
                break;
            default:
                break;
        }
        return event;
    }];
    

    To remove the monitor when not required (assuming you defined it)

    [NSEvent removeMonitor:keyMonitor];
    

提交回复
热议问题