11

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

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

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

我试过了:

  • 调用(和相关selectItem:的)。没有运气,我在文档中看到了一个概念:“请注意,虽然菜单正在跟踪用户输入,但不会反映对菜单的编程更改,例如添加、删除或更改菜单上的项目”NSPopUpButtonNSMenu
  • 发送键盘事件(使用这个答案)。没有运气 - 可能是因为我在发送这些事件的那一刻拿着一些钥匙
  • 查找有关如何通过 Accessibility API 执行此操作的任何信息,但我无法找到有关如何在当前应用程序(甚至任何其他应用程序,但使用 Objective-C)上使用它的任何信息
4

3 回答 3

9

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

NSUInteger idx = [[[menuItem menu] itemArray] indexOfObject:menuItem];
[[menuItem menu] performActionForItemAtIndex:idx];
于 2015-01-20T12:08:07.960 回答
3

打开子菜单: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
}
于 2019-01-23T23:28:10.907 回答
1

除了@LCC 的回答,还可以indexOfItem拨打NSMenu

NSInteger index = [item.menu indexOfItem:item];
[item.menu performActionForItemAtIndex:index];
于 2016-09-05T19:17:14.270 回答