How to popup context menu when clicked on button.

    NSRect frame = [(NSButton *)sender frame];
    NSPoint menuOrigin = [[(NSButton *)sender superview] convertPoint:NSMakePoint(frame.origin.x, frame.origin.y+frame.size.height+40)
                                                               toView:nil];

    NSEvent *event =  [NSEvent mouseEventWithType:NSLeftMouseDown
                                         location:menuOrigin
                                    modifierFlags:NSLeftMouseDownMask // 0x100
                                        timestamp:nil
                                     windowNumber:[[
(NSButton *)sender window] windowNumber]
                                          context:[[
(NSButton *)sender window] graphicsContext]
                                      eventNumber:0
                                       clickCount:1
                                         pressure:1];
   
    NSMenu *menu = [[NSMenu alloc] init];
    [menu insertItemWithTitle:@"add"
                       action:@selector(add:)
                keyEquivalent:@""
                      atIndex:0];

    [NSMenu popUpContextMenu:menu withEvent:event forView:(NSButton *)sender];

Blogged with the Flock Browser

Tags: , , , , ,

Advertisements
Posted in COcoa. 2 Comments »

2 Responses to “How to popup context menu when clicked on button.”

  1. damian Says:

    Hi.
    I created Cocoa Application and add instance of NSButton. I add IBAction method to this button and inside I put your sample code shown above. When I click on button context menu pops up but is not active, I can not select the “add” item because it is disabled. How to make this context menu active??
    thanks

  2. dmetzler Says:

    After creating the menu above, call the following to enable the menu items:

    [menu setAutoenablesItems:NO];


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: