2012-01-27 15 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

@Wesley残念ながら。それでも多くのプロジェクトでそれを使用しています:( – flagman

+9

これはもう少しうまくいくようですね?[theMenu popUpMenuPositioningItem:nil atLocation:[NSEvent mouseLocation] inView:nil]; – Wesley

関連する問題