Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSWindow doesn't receive keyboard events

I creating NSWindow programmatically and i can't receive any keyboard messages. Instead of this i typing in Xcode editor, but my window is in focus at this time. How i can intercept this 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'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;
}
like image 970
user1628106 Avatar asked Nov 04 '22 17:11

user1628106


1 Answers

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

ProcessSerialNumber psn = {0, kCurrentProcess};
OSStatus status =
  TransformProcessType(&psn, kProcessTransformToForegroundApplication);
like image 147
Programmer Doe Avatar answered Nov 09 '22 13:11

Programmer Doe