NSMenu以编程方式选择项目

时间:2014-02-05 16:58:34

标签: objective-c cocoa nsmenu nsmenuitem nspopupbutton

我正在为应用程序编写一个插件 - 自定义键盘快捷键。我可以遍历其观点。 我需要打开弹出菜单,选择其中的项目,然后打开其子菜单并在子菜单中选择一些项目。

现在我只能通过将performClick:发送到相关的NSPopUpButton元素来打开顶部弹出菜单。

如何以编程方式选择菜单中的项目并打开其子菜单?

我试过了:

  • selectItem:(以及相关NSPopUpButton)上致电NSMenu。没有运气,我在doc看到了一个概念:“请注意,当菜单跟踪用户输入时,菜单的程序化更改(如添加,删除或更改菜单上的项目)不会反映出来”
  • 发送键盘事件(使用this answer)。没有运气 - 可能是因为我在发送这些事件时拿着一些钥匙
  • 通过Accessibility API查找有关如何操作的任何信息,但我找不到任何关于如何在当前应用程序(甚至任何其他应用程序,但使用Objective-C)上使用它的信息。

3 个答案:

答案 0 :(得分:8)

使用NSMenu方法- (void)performActionForItemAtIndex:(NSInteger)index

NSUInteger idx = [[[menuItem menu] itemArray] indexOfObject:menuItem];
[[menuItem menu] performActionForItemAtIndex:idx];

答案 1 :(得分:2)

对于打开子菜单:performActionForItemAtIndex:

用于选择和打开菜单:     selectItemAtIndex: + performClick:

请勿在没有子菜单的项目上调用performActionForItemAtIndex:,因为您可能会触发可能由其他人设置的操作。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSMenu *menu = self.popup.menu;
    NSMenuItem *item = [menu itemAtIndex:2];
    [item setAction:@selector(terminate:)];
    [item setTarget:NSApp];
}

- (IBAction)action:(id)sender {
    //[self.popup.menu performActionForItemAtIndex:2]; -> if not submenu this will quit your app
    [self.popup selectItemAtIndex:2]; //-> first select menu item
    [self.popup performClick:nil]; //-> open menu - will not quit app
}

答案 2 :(得分:1)

除了@LCC的回答,您还可以在indexOfItem上致电NSMenu

NSInteger index = [item.menu indexOfItem:item];
[item.menu performActionForItemAtIndex:index];
相关问题