OSX appears to have an asymmetric accessibility API; you can use the NSAccessibilityProtocol to make your own app accessible, but to access accessibility of another app, you have to use a separate set of interfaces/objects, AXUIElement and friends.
I found an article on Retreiving the window that has focus that may be of use here: seems the key steps are:
- Use AXUIElementCreateSystemWide to create a 'system wide' accessibility object
- Ask that object for the currently focused application by calling
AXUIElementCopyAttributeValue
asking for kAXFocusedApplicationAttribute
Ask the returned object for the focused window again using AXUIElementCopyAttributeValue
, but this time for NSAccessibilityFocusedWindowAttribute
- actually looks like you can skip this step below, and go straight from focused application to focused UI Element...
- Ask the returned object for the currently focused element using the same API again, but this time with
NSAccessibilityFocusedUIElementAttribute
- Ask that element for its kAXSizeAttribute / kAXPositionAttribute
You might also want to check out the source code for UIElementInspector which displays information about the element under the mouse pointer (though it doesn't appear to do anything with focus).
Also looks like you'll need to enable the accessibility API either via GUI (see article above) or via terminal for any of the above to work - presumably this is to give users a defense against rogue apps taking control of their desktop.
I haven't used any of these personally (yet); but I'm familiar enough with accessibility APIs to know where to look - hope this helps.