Getting Window Number through OSX Accessibility API

前端 未结 2 690
南方客
南方客 2020-12-07 22:55

I am working on an application that moves windows of third party applications around on the screen.

To get an overview of all currently open windows, I use



        
2条回答
  •  Happy的楠姐
    2020-12-07 23:53

    We ended up hiring a dedicated Accessibility Developer for this task.

    It turns out there is no way to do this without using undocumented APIs (a no go in our case).

    Luckily, there is a practical workaround:

    Loop over all open windows of the app. Get their position, size and title:

    AXUIElementCopyAttributeValue(target, kAXPositionAttribute, CFTypeRef*)&posValue);
    AXUIElementCopyAttributeValue(target, kAXSizeAttribute, (CFTypeRef*)&sizeValue);
    AXUIElementCopyAttributeValue(target, kAXTitleAttribute, (CFTypeRef*)&titleValue);
    

    Next, convert the position and size into actual CGPoint and CGSize values:

    AXValueGetValue(posValue, kAXValueCGPointType, &point);
    AXValueGetValue(sizeValue, kAXValueCGSizeType, &size);
    

    Compare the size, position and title against the values returned by the object in CGWindowListCopyWindowInfo(). If they match, you can safely assume it's the window you were looking for and use the already open AXUIElement (target in our case) to work it.

    The overhead for looping through all open windows turns out to be negligible on OSX. There is a pretty low cap on how many windows are open at the same time.

    Also, while this is not 100% accurate (it is possible that 2 windows have the same position, size and title), we haven't encountered any situation in real usage where this happens so far.

提交回复
热议问题