2012-01-27 20 views
6

Desidero rispondere alla pressione dei tasti di scelta rapida visualizzando NSMenu nella posizione del cursore del mouse.Come posso visualizzare NSMenu nella posizione del cursore del mouse?

La mia domanda è UIElement e non ha una propria finestra.

io ci so è il metodo di NSMenu:

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

ma sembra che non funziona quando non c'è vista :(

Devo creare una visione trasparente falso alla posizione del cursore del mouse. , e quindi visualizzare lì NSMenu, o non v'è modo migliore?

possa esso può essere implementato utilizzando carbonio?

+0

Avete provato a generare una vista falso trasparente? Che succede? –

+0

@RobKeniger - Ho postato una soluzione. Funziona. – flagman

risposta

14

Utilizzare questo invece:

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

Qui è la soluzione che utilizza la finestra trasparente:

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

}

Funziona, ma sto ancora cercando la soluzione più elegante.

+0

hai mai trovato una soluzione migliore? – Wesley

+0

@Wesley Sfortunatamente no. Ancora usando questo in molti progetti :( – flagman

+9

Questo sembra funzionare un po 'meglio? [TheMenu popUpMenuPositioningItem: nil atLocation: [NSEvent mouseLocation] inView: nil]; – Wesley