2011-12-20 61 views
5

我正在研究一個應用程序,我想在當前鼠標位置旁邊顯示一個NSMenu「上下文菜單」。在這一點上,我知道如何從WebView觸發命令來顯示上下文菜單,我似乎無法讓菜單顯示在屏幕上的正確位置。似乎我的座標是從我需要的垂直方向倒置的。這似乎是一個這樣簡單的問題,但我花了很多時間嘗試最佳的「最佳實踐」解決方案。我是否需要找出鼠標所在的屏幕並手動計算y座標?如何在鼠標光標處顯示NSMenu?

這是我非常簡單的代碼靠攏:

- (IBAction)showMenu:(id)sender 
{ 
    CGEventRef ourEvent = CGEventCreate(NULL); 
    CGPoint point = CGEventGetLocation(ourEvent); 
    NSPoint wp = {0,0}; 
    wp = [self.window convertScreenToBase:point]; 
    NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y); 
    NSLog(@"Location? x= %f, y = %f", (float)wp.x, (float)wp.y); 

    NSEvent *event = [NSEvent mouseEventWithType:NSLeftMouseUp location:CGPointMake(wp.x, wp.y) modifierFlags:0 timestamp:NSTimeIntervalSince1970 windowNumber:[_window windowNumber] context:nil eventNumber:0 clickCount:0 pressure:0.1]; 

    //NSEvent *event = [NSEvent eventWithCGEvent:ourEvent]; 


    NSMenu *theMenu = [[NSMenu alloc] initWithTitle:@"Contextual Menu"]; 

    [theMenu insertItemWithTitle:@"Item 1" action:@selector(beep:) keyEquivalent:@"" atIndex:0]; 
    [theMenu insertItemWithTitle:@"Item 2" action:@selector(beep:) keyEquivalent:@"" atIndex:1]; 

    [NSMenu popUpContextMenu:theMenu withEvent:event forView:nil]; 
} 

可有人請我提供的示例代碼來完成這件事的最自然的方式。

回答

7

您正在混合Quartz和Cocoa。 API之間有很多重疊,如果你只能堅持一個,就這樣做。做到這一點,而不是:

NSPoint point = [NSEvent mouseLocation]; 

石英和Cocoa使用不同的座標系:Quartz使用「硬件地址」風格(0,0)在左上角,可可用「數學」風格(0,0座標座標)在左下角。

+0

我以爲我試過了。就在我面前。謝謝! – David 2011-12-20 12:59:56

1

定義在初始化:

NSPoint lastClick; 

然後:

- (void) rightMouseDown:(NSEvent *)theEvent { 
    lastClick = [self convertPoint: theEvent.locationInWindow fromView: nil]; 
    [super rightMouseDown:theEvent]; 
} 

,並在你的行動使用它

- (IBAction)someAction:(id)sender { 
    //Use lastCLick.x and lastClick.y 
}