2
votes

For example, I have an NSMenuItem type variable whose title is "History". I need a keyboard shortcut Meta+h to do the same thing as to click this menu item (pop up a submenu list)..

I think there might be two ways to implement this:

1.bind this menu item to a keyboard shortcut, then the Cocoa will fire the execute the action belongs to the item when the shortcut is fired

2.not binding keyboard shortcut to the item. Create an EventHandler for Meta+h, when the event activated, simulate a mouse click on the menu item.

However, both methods don't work for now.

For the keyboard shortcut, there is a method called setKeyEquivalent, but it uses Command instead of Meta as the modifier. And its result is executing the action binds to the menu item, instead of poping up a submenu.

For the simulating of mouse click, in Cocoa's NSMenuItem reference, I haven't see how to send event like click to a NSMenuItem..

Does anyone have ideas about this? Thanks!

2
You really don't want to simulate mouse clicks with menus unless your building accessibility or automation tools. It requires fiddling with runloopsuchuugaka

2 Answers

2
votes
[menuItem setKeyEquivalent:@" "];  
[menuItem setKeyEquivalentModifierMask:0];  

with any of these modifier key masks (combined using the C bitwise OR operator):

  • NSShiftKeyMask
  • NSAlternateKeyMask
  • NSCommandKeyMask
  • NSControlKeyMask

(BTW, Apple's docs can be really useful!)

0
votes

Your question is slightly unclear -

If you set a shortcut Cocoa will invoke the command for you and your code will never know whether the user used the mouse or hit the key equivalent.

If you'd like to invoke the same command by some other means (key in an NSView, etc). you'd want to manually call the same method that's hooked up to your menu definition.