Cocoa 如何在鼠标光标处显示NSMenu?
我正在开发一个应用程序,希望在当前鼠标位置旁边显示NSMenu“上下文菜单”。在这一点上,我知道如何从WebView触发命令来显示上下文菜单,但我似乎无法使菜单在屏幕上的正确位置显示出来。看起来我的坐标和我需要的垂直方向相反。这似乎是一个很简单的问题,但我花了很多时间尝试最佳的“最佳实践”解决方案。我是否需要找出鼠标所在的屏幕并手动计算y坐标 下面是我非常简单的代码:Cocoa 如何在鼠标光标处显示NSMenu?,cocoa,webkit,nsmenu,Cocoa,Webkit,Nsmenu,我正在开发一个应用程序,希望在当前鼠标位置旁边显示NSMenu“上下文菜单”。在这一点上,我知道如何从WebView触发命令来显示上下文菜单,但我似乎无法使菜单在屏幕上的正确位置显示出来。看起来我的坐标和我需要的垂直方向相反。这似乎是一个很简单的问题,但我花了很多时间尝试最佳的“最佳实践”解决方案。我是否需要找出鼠标所在的屏幕并手动计算y坐标 下面是我非常简单的代码: - (IBAction)showMenu:(id)sender { CGEventRef ourEvent = CGEv
- (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];
}
有人能为我提供最自然的方法来完成这项工作的示例代码吗。您正在将石英与可可混合。API之间有很多重叠,如果您可以只使用一个,那么就这样做。改为这样做:
NSPoint point = [NSEvent mouseLocation];
Quartz和Cocoa使用不同的坐标系:Quartz使用“硬件地址”样式坐标,左上角为(0,0),Cocoa使用“数学”样式坐标,左下角为(0,0)。在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
}