如何在Cocoa应用程序中处理箭头键事件?

Eon*_*nil 12 cocoa keyboard-events

如何在Cocoa应用程序中处理箭头键事件?

Jos*_*ell 16

但是,但是......但我不想成为一个NSResponder子类.

@interface AMonitorNotAResponder : NSObject 
@end
Run Code Online (Sandbox Code Playgroud)
@implementation AMonitorNotAResponder
{
    id eventMonitor;   // An event monitor object; instance of
                       // private class _NSLocalEventObserver
}

- (id)init 
{
    self = [super init];
    if( !self ) return nil;

    NSEvent * (^monitorHandler)(NSEvent *);
    monitorHandler = ^NSEvent * (NSEvent * theEvent){

        switch ([theEvent keyCode]) {
            case 123:    // Left arrow
                NSLog(@"Left behind.");
                break;
            case 124:    // Right arrow
                NSLog(@"Right as always!");
                break;
            case 125:    // Down arrow
                NSLog(@"Downward is Heavenward");
                break;
            case 126:    // Up arrow
                NSLog(@"Up, up, and away!");
                break;
            default:
                break;
        }
        // Return the event, a new event, or, to stop 
        // the event from being dispatched, nil
        return theEvent;
    };

    // Creates an object we do not own, but must keep track
    // of so that it can be "removed" when we're done
    eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask 
                                                         handler:monitorHandler];

    return self;
}

- (void)dealloc 
{
    [NSEvent removeMonitor:eventMon];
}

@end
Run Code Online (Sandbox Code Playgroud)

事件处理指南给出了一些可能的用途.似乎是一个友好的Cocoa版本CGEventTap,或者为某些特定目的绕过响应链的方法.可以监视的事件类型的选择有限,例如,仅按键,而不是向上.该文档纷纷上榜.

也可用:检查使用的任何其他应用程序(无法修改它们)的事件addGlobalMonitorForEventsMatchingMask:handler:.与事件点击一样,此方法需要启用"辅助功能".


Eon*_*nil 11

看到这段代码.我假设该类是子类NSView.

#pragma mark    -   NSResponder

- (void)keyDown:(NSEvent *)theEvent
{
    NSString*   const   character   =   [theEvent charactersIgnoringModifiers];
    unichar     const   code        =   [character characterAtIndex:0];

    switch (code) 
    {
        case NSUpArrowFunctionKey:
        {
            break;
        }
        case NSDownArrowFunctionKey:
        {
            break;
        }
        case NSLeftArrowFunctionKey:
        {
            [self navigateToPreviousImage];
            break;
        }
        case NSRightArrowFunctionKey:
        {
            [self navigateToNextImage];
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

视图应该是接收事件的第一响应者.也许这段代码需要支持.

#pragma mark    -   NSResponder
- (BOOL)canBecomeKeyView
{
    return  YES;
}
- (BOOL)acceptsFirstResponder
{
    return  YES;
}
Run Code Online (Sandbox Code Playgroud)

要使用此方法,该类应该是子类NSResponder.在没有子类化NSResponder的情况下查看其他答案处理.