2011-12-20 64 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 
}