Search code examples
objective-ccocoanswindownswindowcontrollernspanel

How to detect when a NSPanel closes as a result of losing focus? E.g. A user clicking outside of the NSPanel (Window?)


I have a generic NSPanel window that I am using as a preferences window in my app. I have a selector that I call every time the window closes. The purpose of that selector is to save the state of the users chosen preferences (there is no "save" button).

I have an NSButton ("CLOSE") which I easily setup to call my closing selector.

I set it up so that my selector is also called when the user clicks the RED X in the top left corner of the NSPanel by doing:

NSButton *closeButton = [[self window] standardWindowButton:NSWindowCloseButton];
[closeButton setTarget:self];
[closeButton setAction:@selector(myCloseSelector:)];

This works perfectly. My problem though? The window also closes if the user clicks outside of the NSPanel. E.g. If they take their mouse and click on their browser window below the NSPanel that popped up. This also closes the window.

How do I catch my NSPanel losing focus and closing ? I need to ensure that when this happens I also get my selector called.

Thanks!


Solution

  • Made my NSWindowController a delegate for NSWindowDelegate.

    myWindowController.h

    @interface myWindowController : NSWindowController <NSWindowDelegate>
    

    and then set myWindowController as the delegate for my NSPanel.

    Now I can implement:

    - (void) windowDidResignKey:(NSNotification *)notification {
        NSLog(@"Houston...we lost a panel.");
    }
    

    and everything works swimmingly!