2012-08-27 27 views
4

我以编程方式创建NSWindow,但无法接收任何键盘消息。而不是我在Xcode编辑器中输入,但我的窗口在这个时候是焦点。我如何拦截这些事件?NSWindow不会收到键盘事件

这里是我的代码:

//// delegate 
@interface MyDelegate : NSObject 
@end 
@implementation MyDelegate 
@end 

//// view 
@interface MyView : NSView 
@end 

@implementation MyView 

- (BOOL)isOpaque { return YES;} 
- (BOOL)canBecomeKeyView { return YES;} 
- (BOOL)acceptsFirstResponder { return YES;} 

- (void)keyDown:(NSEvent *)event 
{ 
    printf("PRESS\n"); // it's ignoring 
} 

@end 

//// main 
int main(int argc, const char **argv){ 
    [NSApplication sharedApplication]; 

    NSWindow *window = [[NSWindow alloc] 
       initWithContentRect:NSMakeRect(0, 0, 100, 100) 
       styleMask:NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask 
       backing:NSBackingStoreBuffered 
       defer:NO]; 
    [window setContentView: [[MyView alloc] init]]; 
    [window setDelegate: [[MyDelegate alloc] init] ]; 
    [window setAcceptsMouseMovedEvents:YES]; 
    [window setLevel: NSFloatingWindowLevel]; 
    [window makeKeyAndOrderFront: nil]; 

    [NSApp run]; 
    return 0; 
} 

回答

1

你需要使应用前景的应用。这是主窗口接收关键事件所必需的。

ProcessSerialNumber psn = {0, kCurrentProcess}; 
OSStatus status = 
    TransformProcessType(&psn, kProcessTransformToForegroundApplication); 
+0

这帮了我。不知道为什么进程不是默认的前台应用程序... – igagis