7

NSMenuマウスカーソル位置 に表示して、ホットキーの押下に反応したい。

私のアプリケーションにはUIElement、独自のウィンドウがあります。

私は次の方法があることを知っていますNSMenu

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

しかし、ビューがない場合は機能しないようです:(。

マウスカーソルの位置に偽の透明なビューを作成し、そこに表示するNSMenu必要がありますか、それとももっと良い方法がありますか?

Carbonを使用して実装できますか?

4

2 に答える 2

22

代わりにこれを使用してください:

  [theMenu popUpMenuPositioningItem:nil atLocation:[NSEvent mouseLocation] inView:nil];
于 2014-04-19T12:04:19.167 に答える
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]];

}

それは機能しますが、私はまだよりエレガントな解決策を探しています。

于 2012-01-30T06:21:06.660 に答える