NSOpenGLView, NSWindow & NSResponder - makeFirstResponder not working
Asked Answered
R

3

4

In the code below I am Initialising a NSViewController [a NSResponder], with a NSWindow, a NSOpenGLView, presenting the view and attempting to set the NSViewController as the windows first responder.

It is not working. I was expecting to be able to hit a breakpoint in the keyUp: and keyDown: methods also below, but nothing is happening.

Am I missing something?

-(void)initwithFrame:(CGRect)frame 
{
    window = [[MyNSWindow alloc] initWithContentRect:frame styleMask:NSClosableWindowMask | NSTitledWindowMask backing:NSBackingStoreBuffered                           defer: YES ];   


    OpenGLView* glView = [[[OpenGLView alloc] initWithFrame:window.frame] autorelease];

    window.contentView = glView;

    [window makeFirstResponder:self];   
    [window makeKeyWindow];     

    [window display];   
}   

-(void)keyDown:(NSEvent*)theEvent
{
    unichar unicodeKey = [ [ theEvent characters ] characterAtIndex:0 ];
    unicodeKey = 0;
}

-(void)keyUp:(NSEvent *)theEvent
{
    unichar unicodeKey = [ [ theEvent characters ] characterAtIndex:0 ];
    unicodeKey = 0;
}
Rearward answered 19/9, 2011 at 18:13 Comment(0)
R
3

Returning to this issue, actually the problem is elsewhere.

I had been using this sleep function to control the apps frame rate:

void System::Sleep(double seconds)
{
    NSDate* limit       = [NSDate dateWithTimeIntervalSinceNow:seconds];
    NSRunLoop* runLoop  = [NSRunLoop currentRunLoop];

    [runLoop runUntilDate:limit];
}

Doing this seems to freeze the system completely and block the key events.

Instead use this to schedule the update function:

[NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(updateApp:) userInfo:nil repeats:YES];
Rearward answered 24/10, 2011 at 9:58 Comment(0)
T
2

For instances to participate in key-view loops, a custom view must return YES from acceptsFirstResponder.

Teledu answered 20/9, 2011 at 18:53 Comment(2)
Since making this post I have tried adding the following to the view class: -(BOOL)acceptsFirstResponder { return YES; } Did not affect the behaviour.Rearward
@BROK3NS0UL Try something like - (void)keyDown:(NSEvent*)theEvent { NSString *characters = [theEvent characters]; NSLog(@"Key: ", characters); }Stephanystephen
E
2

I had this problem also. This thread might help

keyDown not being called

I found out what was preventing the keyDown event from being called. It was the NSBorderlessWindowMask mask, it prevents the window from become the key and main window. So I have created a subclass of NSWindow called BorderlessWindow:

 @interface BorderlessWindow : NSWindow { }

 @end

 @implementation BorderlessWindow

 - (BOOL)canBecomeKeyWindow {
     return YES; }

 - (BOOL)canBecomeMainWindow {
     return YES; }

 @end
Eger answered 28/3, 2013 at 0:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.