2012-01-27 34 views
6

Tôi muốn phản ứng trên phím bấm nóng bằng cách hiển thị NSMenu tại vị trí con trỏ chuột.Làm thế nào tôi có thể bật lên NSMenu ở vị trí con trỏ chuột?

Đơn đăng ký của tôi là UIElement và không có cửa sổ riêng.

Tôi biết có phương pháp NSMenu:

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

Nhưng có vẻ như nó không hoạt động khi không có điểm :(

Tôi có nên tạo một cái nhìn minh bạch giả tại vị trí con trỏ chuột. , và sau đó hiển thị có NSMenu, hoặc có cách nào tốt hơn?

có thể nó có thể được thực hiện bằng Carbon?

+0

Bạn đã cố gắng tạo ra một cái nhìn giả trong suốt? Chuyện gì xảy ra? –

+0

@RobKeniger - Tôi đã đăng giải pháp. Nó hoạt động. – flagman

Trả lời

14

Sử dụng này để thay thế:

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

Đây là giải pháp trong đó sử dụng cửa sổ trong suốt:

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

}

Nó hoạt động, nhưng tôi vẫn đang tìm kiếm giải pháp thanh lịch hơn.

+0

bạn đã bao giờ tìm thấy giải pháp tốt hơn chưa? – Wesley

+0

@Wesley Thật không may là không. Vẫn sử dụng nó trong nhiều dự án: ( – flagman

+9

Điều này dường như làm việc tốt hơn một chút? [TheMenu popUpMenuPositioningItem: nil atLocation: [NSEvent mouseLocation] inView: nil]; – Wesley

Các vấn đề liên quan