Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 751
Pedro Vieira Avatar asked Dec 31 '12 00:12

Pedro Vieira


1 Answers

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; 
}
like image 70
sudo rm -rf Avatar answered Oct 07 '22 08:10

sudo rm -rf