Cocoa 如何在鼠标光标位置弹出菜单?
我想通过在鼠标光标位置显示Cocoa 如何在鼠标光标位置弹出菜单?,cocoa,nsview,nsmenu,Cocoa,Nsview,Nsmenu,我想通过在鼠标光标位置显示NSMenu对热键按下做出反应 我的应用程序是UIElement,没有自己的窗口 我知道有一种NSMenu的方法: -(void)popUpContextMenu:(NSMenu *)menu withEvent:(NSEvent *)event forView:(NSView *)view; 但是,当没有视图时,它似乎不起作用:( 我应该在鼠标光标位置创建一个伪透明视图,然后在那里显示NSMenu,还是有更
NSMenu
对热键按下做出反应
我的应用程序是UIElement
,没有自己的窗口
我知道有一种NSMenu
的方法:
-(void)popUpContextMenu:(NSMenu *)menu
withEvent:(NSEvent *)event
forView:(NSView *)view;
但是,当没有视图时,它似乎不起作用:(
我应该在鼠标光标位置创建一个伪透明视图,然后在那里显示NSMenu
,还是有更好的方法
是否可以使用碳来实现此功能?以下是使用透明窗口的解决方案:
+ (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]];
}
它可以工作,但我仍在寻找更优雅的解决方案。使用以下方法:
[theMenu popUpMenuPositioningItem:nil atLocation:[NSEvent mouseLocation] inView:nil];
你试过创建一个虚假的透明视图吗?会发生什么事?@RobKeniger-我发布了一个解决方案。它很有效。你找到过更好的解决方案吗?@Wesley不幸没有。在许多项目中仍然使用它:(这似乎效果更好一些?[theMenu PopupMenuPositionGitem:nil atLocation:[NSEvent mouseLocation]inView:nil];哇:)在方法描述中看起来很好且正确。“如果视图为零,则位置将在屏幕坐标系中解释。这允许您弹出一个与任何窗口断开连接的菜单。”谢谢。@Wesley回答得很好!您为我节省了很多时间…:-)