寻找popUpMenuPositioningItem:atLocation:inView:相当于10.5

时间:2010-02-04 22:26:45

标签: cocoa contextmenu osx-leopard nsmenu

我正在开发一个需要在各种场景下在屏幕上显示上下文菜单的应用程序。在我写的函数中,我无法访问任何NSWindows或NSView。我想使用popUpMenuPositioningItem:atLocation:inView,因为这个函数在10.6中对我很有效。但是,我们需要支持10.5,因此我无法使用此功能。

我最感兴趣的功能,如文档中所述:

  

如果视图为零,则位置为   在屏幕坐标中解释   系统。这允许你弹出一个   菜单与任何窗口断开连接。

基本上,我需要在屏幕上显示给定位置的上下文菜单,但没有任何关联的视图。

有没有办法在10.5上实现这个目标?

2 个答案:

答案 0 :(得分:1)

// Set up the button cell, converting to NSView coordinates. The menu is
// positioned such that the currently selected menu item appears over the
// popup button, which is the expected Mac popup menu behavior.
NSPopUpButtonCell* button = [[NSPopUpButtonCell alloc] initTextCell:@""
                                                          pullsDown:NO];
[button autorelease];
[button setMenu:menu_];
// We use selectItemWithTag below so if the index is out-of-bounds nothing
// bad happens.
[button selectItemWithTag:index];
[button setFont:[NSFont menuFontOfSize:fontSize_]];

// Create a dummy view to associate the popup with, since the OS will use
// that view for positioning the menu.
NSView* dummyView = [[[NSView alloc] initWithFrame:bounds] autorelease];
[view addSubview:dummyView];
NSRect dummyBounds = [dummyView convertRect:bounds fromView:view];

// Display the menu, and set a flag if a menu item was chosen.
[button performClickWithFrame:dummyBounds inView:dummyView];

if ([self menuItemWasChosen])
  index_ = [button indexOfSelectedItem];

[dummyView removeFromSuperview];

答案 1 :(得分:0)

我不知道如何在Cocoa中执行此操作,但您可以使用Carbon函数PopUpMenuSelect。