2012-08-27 44 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