如何在鼠标光标显示NSMenu? [英] How Can I Show NSMenu at Mouse Cursor?

查看:431
本文介绍了如何在鼠标光标显示NSMenu?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,我想在当前鼠标位置旁边显示一个NSMenu上下文菜单。在这一点上,我知道如何从WebView触发命令来显示上下文菜单,我似乎不能得到菜单显示在屏幕上正确的位置。看起来我的坐标是从我需要的垂直翻转。这似乎是这样一个简单的问题,但我花了一点时间试图最好的最佳实践解决方案。

I am working on an app where I want to show an NSMenu "context menu" next to the current mouse location. At this point, I know how to trigger the command from the WebView to show the context menu, I just can't seem to get the menu to show up at the correct placement on the screen. It seems like my coordinates are inverted vertically from what I need. This seems like such a simple problem, but I have spent a good bit of time trying to best a "best practices" solution. Do I need to figure out which screen the mouse is in and calculate the y coordinate manually?

这是我真正简单的代码:

Here is my really simple code that gets close:

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

有人可以用最自然的方式提供样例代码。

Can someone please provide me sample code for the most natural way to get this done.

推荐答案

您正在混合Quartz和Cocoa。 API之间有很多重叠,如果你只能坚持一个,这样做。请改为:

You are mixing Quartz with Cocoa. There is a lot of overlap between the APIs, and if you can stick with just one, do so. Do this instead:

NSPoint point = [NSEvent mouseLocation];

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

Quartz and Cocoa use different coordinate systems: Quartz uses "hardware address" style coordinates with (0, 0) at the top left, Cocoa uses "mathematics" style coordinates with (0, 0) at the bottom left.

这篇关于如何在鼠标光标显示NSMenu?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆