我以编程方式创建NSWindow,但我无法接收任何键盘消息。而不是我输入Xcode编辑器,但此时我的窗口是焦点。我如何拦截这些事件?
这是我的代码:
//// 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;
}
答案 0 :(得分:1)
您需要将应用程序设置为前台应用程序。这是主窗口接收关键事件所必需的。
ProcessSerialNumber psn = {0, kCurrentProcess};
OSStatus status =
TransformProcessType(&psn, kProcessTransformToForegroundApplication);