Dav*_*vid 5 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];
}
Run Code Online (Sandbox Code Playgroud)
有人可以提供示例代码,以最自然的方式来完成这项工作.
你正在混合Quartz和Cocoa.API之间有很多重叠,如果你只坚持一个,那就这样做.改为:
NSPoint point = [NSEvent mouseLocation];
Run Code Online (Sandbox Code Playgroud)
Quartz和Cocoa使用不同的坐标系:Quartz在左上角使用"硬件地址"样式坐标(0,0),Cocoa在左下角使用"数学"样式坐标和(0,0).
| 归档时间: |
|
| 查看次数: |
3749 次 |
| 最近记录: |