How to list all windows from all workspaces in Python on Mac?

后端 未结 2 1211
囚心锁ツ
囚心锁ツ 2020-12-19 15:25

The following Python 2 code prints list of all windows in the current workspace:

#!/usr/bin/python
import Quartz
for window in Quartz.CGWindowListCopyWindowI         


        
2条回答
  •  北海茫月
    2020-12-19 16:12

    The key is here to use the right option for the 1st argument of CGWindowListCopyWindowInfo. So apart of using optionOnScreenOnly property (which list all windows that are currently onscreen), excludeDesktopElements property needs to be added.

    excludeDesktopElements: Exclude any windows from the list that are elements of the desktop, including the background picture and desktop icons.

    E.g.

    list = CGWindowListCopyWindowInfo(kCGWindowListExcludeDesktopElements | kCGWindowListOptionOnScreenOnly, kCGNullWindowID)
    

    Alternatively for all windows, kCGWindowListOptionAll property can be also used.

    kCGWindowListOptionAll: List all windows, including both onscreen and offscreen windows. When retrieving a list with this option, the relativeToWindow parameter should be set to kCGNullWindowID.

    For other properties, check CGWindow.h in CoreGraphics.


    So the original code can be changed to:

    #!/usr/bin/python
    # Prints list of all windows.
    # See: https://stackoverflow.com/q/44232433/55075
    import Quartz
    for window in Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListOptionOnScreenOnly | Quartz.kCGWindowListExcludeDesktopElements, Quartz.kCGNullWindowID):
        print("%s - %s" % (window['kCGWindowOwnerName'], window.get('kCGWindowName', u'Unknown').encode('ascii','ignore')))
    

提交回复
热议问题