如何在鼠标光标处显示NSMenu?

时间:2011-12-20 05:50:22

标签: cocoa webkit nsmenu

我正在开发一个应用程序,我想在当前鼠标位置旁边显示一个NSMenu“上下文菜单”。此时,我知道如何从WebView触发命令来显示上下文菜单,我似乎无法让菜单显示在屏幕上的正确位置。看起来我的坐标是从我需要的垂直方向倒置的。这似乎是一个简单的问题,但我花了很多时间来尝试最好的“最佳实践”解决方案。我是否需要确定鼠标所在的屏幕并手动计算y坐标?

这是我非常简单的代码:

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

有人可以提供示例代码,以便以最自然的方式完成此任务。

2 个答案:

答案 0 :(得分:7)

您正在将Quartz与Cocoa混合。 API之间有很多重叠,如果你只坚持一个,那就这样做。这样做:

NSPoint point = [NSEvent mouseLocation];

Quartz和Cocoa使用不同的坐标系:Quartz在左上角使用“硬件地址”样式坐标(0,0),Cocoa在左下角使用“数学”样式坐标和(0,0)。

答案 1 :(得分:1)

在init中定义:

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
}