NSMenu programmatically selects an item

I am writing a plugin for an application - a custom key combination. I can go through his eyes. I need to open a popup menu, select an item in it, then open its submenu and select an item in the submenu.

Now I can only open the popup menu by sending performClick: to the corresponding NSPopUpButton element.

How to programmatically select an item in a menu and open its submenu?

I tried:

  • calling selectItem: on NSPopUpButton (and the associated NSMenu ). Unlucky, and I see the concept in the doc : "Note that when the menu tracks user input, programmatic changes to the menu are such as adding, removing or changing items in the menu is not reflected"
  • send keyboard events (using this answer ). No luck - maybe because I hold several keys at the time of sending these events.
  • to find information on how to do this using the Accessibility API, but I just can't find anything about how to use it in the current application (or even in any other application, but with Objective-C)
+7
objective-c cocoa nsmenu nsmenuitem nspopupbutton
source share
3 answers

Use the NSMenu method - (void)performActionForItemAtIndex:(NSInteger)index

 NSUInteger idx = [[[menuItem menu] itemArray] indexOfObject:menuItem]; [[menuItem menu] performActionForItemAtIndex:idx]; 
+7
source share

In addition to @LCC's answer, you can also call indexOfItem on NSMenu

 NSInteger index = [item.menu indexOfItem:item]; [item.menu performActionForItemAtIndex:index]; 
0
source share

To open the submenu: performActionForItemAtIndex:

To select and open the menu: selectItemAtIndex: + performClick:

Do not call performActionForItemAtIndex: for an element that does not have a submenu, as you can initiate an action that could have been set by someone else.

 - (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 } 
0
source share

All Articles