【问题标题】:How Can I Show NSMenu at Mouse Cursor?如何在鼠标光标处显示 NSMenu?
【发布时间】:2012-01-24 04:09:15
【问题描述】:

我正在开发一个应用程序,我想在当前鼠标位置旁边显示一个 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];
}

有人可以提供示例代码,以最自然的方式完成这项工作。

【问题讨论】:

    标签: cocoa webkit nsmenu


    【解决方案1】:

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

    NSPoint point = [NSEvent mouseLocation];
    

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

    【讨论】:

      【解决方案2】:

      在初始化中定义:

      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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-30
        • 1970-01-01
        • 2012-09-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多