如何在NSObjectController中使用keyDown

时间:2014-07-03 17:19:33

标签: macos keydown xcode5.1 nsobjectcontroller

我正在使用Xcode5为MacOSX开发一个ap

我的初始窗口是基于NSObjectController的,我试图通过使用我在NSWindowControllers上使用的常用方法来捕获键盘事件

-(void)keyDown:(NSEvent *)theEvent{}

但这并没有捕获任何东西......是否还有其他任何方法来完成这样的任务????

提前感谢支持

1 个答案:

答案 0 :(得分:1)

还有另一种方法可以让它在NSObjectController上运行......

这样可以捕获左键和右键......

@interface MyNSObjectController(){
    id          eventMonitor; 
}

@end

@implementation MyNSObjectController
- (void) awakeFromNib{
    [self captureKeyDownEvents];
}

-(void)captureKeyDownEvents{
    NSEvent  *(^handler)(NSEvent*)  = ^(NSEvent *theEvent) {
        NSObjectController *targetWindow          = self;
        if (targetWindow != self) {
            return theEvent;
        }

        NSEvent *result = theEvent;
        if (theEvent.keyCode == 123) { //left arrow
            NSLog(@"you just pressed left key");
            result = nil;
        }

        if (theEvent.keyCode == 124) { //right arrow
            NSLog(@"you just pressed right key");
            result = nil;
        }

        return result;
    };
    eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:handler];
}

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

@end