Pedro Vieira
Pedro Vieira

Reputation: 3370

NSWindow is not receiving any notification when it loses focus

I have a custom NSWindow class that has the following methods:

- (void)setupWindowForEvents{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:) name:NSWindowDidResignMainNotification object:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignKey:) name:NSWindowDidResignKeyNotification object:self];
}

-(void)windowDidResignKey:(NSNotification *)note {
    NSLog(@"notification");
    [self close];
}

I call [_window setupWindowForEvents]; but the windowDidResignKey never gets called.
This is how I call my NSWindow: when the status bar item is clicked I makeKeyAndOrderFront and the Window is displayed right beneath the status bar item, like this:enter image description here

Any ideas why the I don't get any notification when the window loses focus? I've used both NSWindowDidResignMainNotification and NSWindowDidResignKeyNotification to see if any of these worked, but none is working.

Upvotes: 9

Views: 4530

Answers (1)

sudo rm -rf
sudo rm -rf

Reputation: 29524

You're probably not getting the notification because you actually are never key in the first place. Your window appears to be borderless, and borderless windows don't grab key window status by default.

In your window subclass, be sure to return YES on the following methods:

- (BOOL)canBecomeKeyWindow { 
    return YES; 
}

- (BOOL)canBecomeMainWindow { 
    return YES; 
}

Upvotes: 12

Related Questions