0
votes

In my MAC app, in one use case, I prompt an window to the user and give him 2 options (say buttons Save and Cancel). I want to force the user to select either of the 2 buttons to close the window.

But currently I find that if the user hits "Command + w" key when window has the focus, the window gets closed. In the .xib resource file, I uncheck the "close" option but that only disables the close option in the window UI.

How do I make sure that my window ignores the "Command+w" key and stays as is without closing.

Have also tried removing the notification by adding below code in awakeFromNib method but did not help.

[[NSNotificationCenter defaultCenter] removeObserver:NSWindowWillCloseNotification ];

Have also tried to implement "windowShouldClose" delegate method and return NO, but this method is never called. The documentation too says that this method is not reliable.

2

2 Answers

0
votes

I recently had to solve a similar problem. I'm not sure that this is the 'right' way to do it. But it worked for my purposes, and might work for you.

By default, I think, the 'Close Window' (CMD+W) menu item is bound to the action 'performClose' on first-responder. If you remove this binding and instead bind to a custom IBAction on your application delegate or main window controller, it allows you to conditionally call the close method of the current key-window if it is not matching the instance that you want to keep alive.

@property (strong, nonatomic) MyWindowController *unstoppable;
-(IBAction)killActiveWindow:(id)sender
{   
    NSWindow *keyWindow = [[NSApplication sharedApplication]keyWindow];
    if ([keyWindow isNotEqualTo: unstoppable.window]){
        NSLog(@" CMD+W Closing Window %@",keyWindow.title);
        [keyWindow close];
    }
}
0
votes

You should use an NSAlert for this sort of prompt, probably run as a sheet on the window. That would avoid the problem of closing it.

In any case, the window's delegate can implement -windowShouldClose: to control if a window is allowed to close. You can make an object (often the window controller) be its delegate by declaring that it adopts the NSWindowDelegate protocol and connecting the window's delegate outlet to that object.