2012-01-27 3 views
6

NSMenu을 마우스 커서 위치에 표시하여 바로 가기 키를 눌러야합니다.NSMenu를 마우스 커서 위치에서 팝업 할 수 있습니까?

내 응용 프로그램은 UIElement이며 자체 창이 없습니다.

내가 거기에 알고는 NSMenu의 방법입니다 :

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

그러나 더보기 :(이없는 경우가 작동하지 않는 것 같습니다

나는 마우스 커서 위치에 가짜 투명 뷰를 작성해야합니다. 다음이 NSMenu을 표시, 또는 더 나은 방법은 무엇입니까?

그것은 탄소를 사용하여 구현 될 수있다?

+0

당신이 가짜 투명 뷰를 생성 시도? 무슨 일이야? –

+0

@RobKeniger - 해결책을 게시했습니다. 그것은 작동합니다. – flagman

답변

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

+0

@ 웨슬리 안타깝게도. 여전히 많은 프로젝트에서 이것을 사용하고 있습니다 : ( – flagman

+9

)이 기능이 약간 더 효과적입니다. [theMenu popUpMenuPositioningItem : nil atLocation : [NSEvent mouseLocation] inView : nil]; – Wesley

관련 문제