Search code examples
objective-ccocoanswindownsmenuitem

Enabling and Disabling Generic Window Menu Command


When you let the application open a window (NSWindow), a command after the name of that window appears under the Window menu as shown below where one of the commands points to the main application window and the other points to the opened window.

enter image description here

Provided that I know the name of the window the user is going to show, how do I enable and disable that command? I suppose the following is not going to work.

- (void)closeGenericWindow {
    NSString *windowName = NSLocalizedString(@"controlListWindow",@"");
    NSMenuItem *windowMenuItem = [[NSMenuItem alloc] initWithTitle:windowName action:nil keyEquivalent:@""];
    [windowMenuItem setEnabled:NO];
}

I've run a search for '[objective-c] [cocoa] disable window.' I don't find anything relevant except this topic, which suggests that I create an IBOutlet in the header. But the command itself doesn't exist until the user actually chooses to open the window in question.

Muchos thankos


Solution

  • There are probably a couple of approaches to this:

    • First, you can set the window's excludedFromWindowsMenu property to YES to simply exclude the window from the menu.
    • Similarly, windows with no title do not appear in that menu.
    • Finally, you can override -canBecomeKeyWindow to return NO and that should disable that menu, I think. You may need to override -canBecomeMainWindow instead or in addition.