2012-01-27 90 views
6

我想通过在鼠标光标位置显示NSMenu来对热键按下作出反应。我如何在鼠标光标位置弹出NSMenu?

我的申请是UIElement,没有自己的窗口。

我知道有一种方法NSMenu

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

但似乎在没有观点:(这是行不通的

我应该建立在鼠标光标位置的假透明的视图。 ,然后显示有NSMenu,或者有更好的办法?

愿它可以用碳来实现?

+0

您是否尝试过创建一个假的透明看法?怎么了? – 2012-01-27 22:05:42

+0

@RobKeniger - 我发布了解决方案。有用。 – flagman 2012-01-30 06:22:25

回答

14

使用这个代替:

[theMenu popUpMenuPositioningItem:nil atLocation:[NSEvent mouseLocation] inView:nil]; 
1

这是解决方案,它采用透明视窗:

+ (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]]; 

}

它的工作原理,但我仍然在寻找更好的解决方案。

+0

你有没有找到更好的解决方案? – Wesley 2013-02-17 20:47:00

+0

@韦斯利很遗憾没有。仍然在很多项目中使用:( – flagman 2013-02-18 06:44:06

+9

这似乎工作更好?[theMenu popUpMenuPositioningItem:nil atLocation:[NSEvent mouseLocation] inView:nil]; – Wesley 2013-02-18 07:09:14