How can I open NSMenu at the position of the mouse cursor?

I want to respond to a hotkey by showing NSMenu at the position of the mouse cursor.

My application is UIElement and does not have its own window.

I know there is an NSMenu method:

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

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

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

Could this be implemented using Carbon?

+6
source share
2 answers

Use this instead:

  [theMenu popUpMenuPositioningItem:nil atLocation:[NSEvent mouseLocation] inView:nil]; 
+14
source

Here is a solution that uses a 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]]; 

}

This works, but I'm still looking for a more elegant solution.

+1
source

Source: https://habr.com/ru/post/907018/


All Articles