如何在Mac上的Python中列出所有工作区中的所有窗口? [英] How to list all windows from all workspaces in Python on Mac?
本文介绍了如何在Mac上的Python中列出所有工作区中的所有窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下Python 2代码打印当前工作区中所有窗口的列表:
The following Python 2 code prints list of all windows in the current workspace:
#!/usr/bin/python
import Quartz
for window in Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID):
print("%s - %s" % (window['kCGWindowOwnerName'], window.get('kCGWindowName', u'Unknown').encode('ascii','ignore')))
尽管它不会打印全屏显示的应用程序(因为它位于另一个工作区中).
Although it doesn't print the applications which are in full screen (as it's in another workspace).
如何修改上述脚本以列出所有桌面上的所有窗口?
How do I modify above script to list all windows from all desktops?
推荐答案
以下脚本应返回任何桌面/工作区/显示器,全屏和详细信息(坐标,pid,标题等)上的窗口信息:>
The following script should return window information on any desktop/workspace/display, fullscreen, and detailed information (coordinates, pid, titles, etc.):
#!/usr/bin/python
import Quartz
import time
from Quartz import CGWindowListCopyWindowInfo, kCGWindowListExcludeDesktopElements, kCGNullWindowID
from Foundation import NSSet, NSMutableSet
def windowList(wl):
for v in wl:
print (
str(v.valueForKey_('kCGWindowOwnerPID') or '?').rjust(7) +
' ' + str(v.valueForKey_('kCGWindowNumber') or '?').rjust(5) +
' {' + ('' if v.valueForKey_('kCGWindowBounds') is None else (
str(int(v.valueForKey_('kCGWindowBounds').valueForKey_('X'))) + ',' +
str(int(v.valueForKey_('kCGWindowBounds').valueForKey_('Y'))) + ',' +
str(int(v.valueForKey_('kCGWindowBounds').valueForKey_('Width'))) + ',' +
str(int(v.valueForKey_('kCGWindowBounds').valueForKey_('Height')))
) ).ljust(21) + '}' +
'\t[' + ((v.valueForKey_('kCGWindowOwnerName') or '') + ']') +
('' if v.valueForKey_('kCGWindowName') is None else (' ' +
v.valueForKey_('kCGWindowName') or ''))
).encode('utf8') # remove 'encode' for Python 3.x
wl1 = CGWindowListCopyWindowInfo(kCGWindowListExcludeDesktopElements, kCGNullWindowID)
print('Move target window (or ignore)\n')
time.sleep(5)
print('PID'.rjust(7) + ' ' + 'WinID'.rjust(5) + ' ' + 'x,y,w,h'.ljust(21) + ' ' + '\t[Title] SubTitle')
print('-'.rjust(7,'-') + ' ' + '-'.rjust(5,'-') + ' ' + '-'.ljust(21,'-') + ' ' + '\t-------------------------------------------')
wl2 = CGWindowListCopyWindowInfo(kCGWindowListExcludeDesktopElements, kCGNullWindowID)
w = NSMutableSet.setWithArray_(wl1)
w.minusSet_(NSSet.setWithArray_(wl2))
wl = Quartz.CGWindowListCopyWindowInfo( Quartz.kCGWindowListOptionAll, Quartz.kCGNullWindowID)
wl = sorted(wl, key=lambda k: k.valueForKey_('kCGWindowOwnerPID'))
windowList(wl)
print('\nDetailed window information: {0}\n'.format(w))
这篇关于如何在Mac上的Python中列出所有工作区中的所有窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文