NSWindow does not receive keyboard events

I am creating NSWindow programmatically and I cannot receive any keyboard messages. Instead, I type in the Xcode editor, but at this time my window is in focus. How can I intercept these events?

Here is my code:

//// 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 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; } 
+4
source share
1 answer

You need to make the application a priority. This is necessary for the main window to receive key events.

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

All Articles