In this post, we are going to look at how to retrieve the window that has focus, that does not necessarily belong to your app. For this to be possible, you MUST have enabled access for assistive devices in the “Universal Access” Preference Pane.

Ensure the "Enable access for assistive devices" is checked

Firstly, we need to check if the preference has been set. To do this we have to use one of the Accessibility APIs.

    Boolean AXAPIEnabled (void);

This method returns true if the access for assistive devices have been enabled. False, otherwise. If access has not been enabled, we will inform the user to enable it and quit the app(for now. Next post we will look at how to open the preference pane).

Secondly, we need to create a system wide element that can listen to focused accessibility object regardless of which application is currently active.

    AXUIElementRef AXUIElementCreateSystemWide (void);

We have to use this element to retrieve information about the focused application and then focused window. We cannot get the focused window directly. Therefore, we have to first get the application that is in focus and the get the window that is in focus. Note: We can only get copies of the above mentioned information. To do this, we have to use the following method.

    AXError AXUIElementCopyAttributeValue (
        AXUIElementRef element,
        CFStringRef attribute,
        CFTypeRef *value);

The allowed attributes can be found here. ‘Value’ refers to the value associated with the specified attribute. Thats it folks. Now we can look at the actual implementation.

Implementation

    AXUIElementRef _systemWideElement;
    if(!AXAPIEnabled()){
        //exit
    }
    AXUIElementRef _focusedApp;
    CFTypeRef _focusedWindow;
    _systemWideElement = AXUIElementCreateSystemWide();
    AXUIElementCopyAttributeValue(_systemWideElement,
                         (CFStringRef)kAXFocusedApplicationAttribute,(CFTypeRef*)&_focusedApp);
    AXUIElementCopyAttributeValue((AXUIElementRef)_focusedApp,
                         (CFStringRef)NSAccessibilityFocusedWindowAttribute,(CFTypeRef*)&_focusedWindow)

That is all for now! Good luck. Comments are welcome.

Tags: , , , , , , ,