How can i pop up NSMenu at mouse cursor position?

6.4k Views Asked by At

I want to react on hot key press by displaying NSMenu at mouse cursor position.

My application is UIElement and doesn't have its own window.

I know there is method of NSMenu :

-(void)popUpContextMenu:(NSMenu *)menu
              withEvent:(NSEvent *)event
                forView:(NSView *)view;

But it seems it doesn't work when there is no view :(.

Should I create a fake transparent view at mouse cursor position, and then display there NSMenu, or there is better way?

May it can be implemented using Carbon?

2

There are 2 best solutions below

0
On BEST ANSWER

Use this instead:

  [theMenu popUpMenuPositioningItem:nil atLocation:[NSEvent mouseLocation] inView:nil];
6
On

Here is solution which uses transparent window:

+ (NSMenu *)defaultMenu {
    NSMenu *theMenu = [[[NSMenu alloc] initWithTitle:@"Contextual Menu"] autorelease];
    [theMenu insertItemWithTitle:@"Beep" action:@selector(beep:) keyEquivalent:@"" atIndex:0];
    [theMenu insertItemWithTitle:@"Honk" action:@selector(honk:) keyEquivalent:@"" atIndex:1];
    return theMenu;
}

- (void) hotkeyWithEvent:(NSEvent *)hkEvent 
{
    NSPoint mouseLocation = [NSEvent mouseLocation];

    // 1. Create transparent window programmatically.

    NSRect frame = NSMakeRect(mouseLocation.x, mouseLocation.y, 200, 200);
    NSWindow* newWindow  = [[NSWindow alloc] initWithContentRect:frame
                                                     styleMask:NSBorderlessWindowMask
                                                       backing:NSBackingStoreBuffered
                                                         defer:NO];
    [newWindow setAlphaValue:0];
    [newWindow makeKeyAndOrderFront:NSApp];

    NSPoint locationInWindow = [newWindow convertScreenToBase: mouseLocation];

    // 2. Construct fake event.

    int eventType = NSLeftMouseDown;

    NSEvent *fakeMouseEvent = [NSEvent mouseEventWithType:eventType 
                                                 location:locationInWindow
                                            modifierFlags:0
                                                timestamp:0
                                             windowNumber:[newWindow windowNumber]
                                                  context:nil
                                              eventNumber:0
                                               clickCount:0
                                                 pressure:0];
    // 3. Pop up menu
    [NSMenu popUpContextMenu:[[self class]defaultMenu] withEvent:fakeMouseEvent forView:[newWindow contentView]];

}

It works, but i'm still looking for more elegant solution.