NSWindow is not receiving any notification when it loses focus
Asked Answered
A

1

9

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.

Alternative answered 31/12, 2012 at 0:45 Comment(0)
E
12

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; 
}
Emmittemmons answered 31/12, 2012 at 1:15 Comment(2)
thank you so much, completely forgot about that. btw, can u please explain me the difference between the notifications NSWindowDidResignMainNotification and NSWindowDidResignKeyNotification?Alternative
Good question. Key windows are ones which currently have the first responder status and respond to user input. Main windows are just like key windows, except they don't necessarily need to have first responder status. Both states appear focused. This might be of use to you: developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/…Emmittemmons

© 2022 - 2024 — McMap. All rights reserved.