Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macos x Shortcuts of a Application

I need to read all Shortcuts of the frontmost Application in MAC OS. Is there a API or Class in Cocoa,Objective-c who provides this?

like image 541
Togo Avatar asked Feb 20 '23 05:02

Togo


1 Answers

The Accessibility API is what you need. Unfortunately, it is rather convoluted, and it would be good to read through the UIElementInspector source code to see how it's used, as well as the sections relevant to assistive applications in the Accessibility Programming Guidelines for Mac.

What you want would take a good bit of code so I will just outline the steps.

  1. Use [[NSWorkspace sharedWorkspace] runningApplications] to get a list of applications and get the application whose active property is YES.
  2. Get the PID of that application using the NSRunningApplication's processIdentifier property.
  3. Now we get to Accessibility, accessed through the Application Services API
  4. Create an AXUIElement representing the active Application using AXUIElementCreateApplication, which takes pid as the argument.
  5. Now you have an AXUIElement with the Application role, or AXApplication pseudo-class. You'll want to proceed down the hierarch of elements AXApplication -> AXMenuBar -> AXMenuBarItem -> AXMenuItem. Note that AXMenuItems can have other AXMenuItems nested under them.
  6. To traverse the hierarchy, use AXUIElementCopyAttributeValues to get the values of kAXChildrenAttribute. This will return an array of children AXUIElements.
  7. Finally, when you get to AXMenuItem elements, examine their Menu Item Cmd Char, Glyph, Modifiers, and Virtual Key attributes for the actual shortcuts. The constants for the attribute names, like kAXMenuItemCmdCharAttribute, are listed here.
like image 92
Yunchi Avatar answered Feb 28 '23 00:02

Yunchi