Displaying a Contextual Menu

The Application Kit interprets right-mouse-down events and left-mouse-down events modified by the Control key as commands to display a contextual menu for the clicked view. Your view subclasses have several alternative approaches for displaying a contextual menu:

After you complete any of these procedures, the Application Kit displays the contextual menu whenever the user left-Control-clicks or right-clicks the view. Note that the Application Kit automatically also validates the menu items of contextual menus, unless you request it not to.

If you need to customize the contextual menu, you can do so by setting an appropriate object as the menu’s delegate and implementing the menuWillOpen: method to customize the menu as you see fit just before it appears.

If you want your view to display a contextual menu in response to events other than right-mouse clicks and left-mouse-Control clicks, you can directly handle the event message in the appropriate NSResponder method. For example, if you want users to be able to left-click an image view to get a menu of export options, you would override the mouseDown: method. In your implementation of the method, create a menu and then invoke the NSMenu class method popUpContextMenu:withEvent:forView:, passing in the event object related to the mouse-down event and the view owning the contextual menu. Listing 1 illustrates this approach.

Listing 1  Displaying a contextual menu upon receiving a left-mouse event

- (void)mouseDown:(NSEvent *)theEvent {
 
    NSMenu *theMenu = [[NSMenu alloc] initWithTitle:@"Contextual Menu"];
    [theMenu insertItemWithTitle:@"Beep" action:@selector(beep:) keyEquivalent:@"" atIndex:0];
    [theMenu insertItemWithTitle:@"Honk" action:@selector(honk:) keyEquivalent:@"" atIndex:1];
 
    [NSMenu popUpContextMenu:theMenu withEvent:theEvent forView:self];
}

Contextual menus, including any menu you pop up with popUpContextMenu:withEvent:forView:, automatically insert menu items from any contextual menu plug-ins that the user has installed into the menu. A contextual menu plug-in, which is CFPlugIn bundle installed in a Library/Contextual Menu Items directory at the appropriate level of the system, enables applications and other forms of software to extend the list of commands found on contextual menus such as the Finder’s. The applications do not have to be running for their items to appear. If you are trying to programmatically display a menu, you might not want those items to appear. The preferred approach for programmatically displaying a non-contextual menu is to create an NSPopUpButtonCell object, set its menu, and then call send a attachPopUpWithFrame:inView: message to the pop-up button cell.