有没有办法迭代Mac OS X中所有打开的窗口?

Ale*_*lex 3 macos cocoa applescript

当您从笔记本电脑上拔下具有更高分辨率的外接显示器时,窗口大部分会保留其宽度,但是它们的大小会被剪切到macbook屏幕的(较小)高度.当您重新插入显示器时,它们的尺寸仍然非常小.

我的问题是:有没有什么方法可以迭代所有打开的窗口,保存它们的大小,并在监视器重新插入后恢复它们?

Ann*_*nne 10

以下AppleScript演示如何:

  • 遍历所有窗口
  • 检索并更改窗口位置
  • 检索并更改窗口大小

码:

tell application "System Events"
    set theProcesses to application processes
    repeat with theProcess from 1 to count theProcesses
        tell process theProcess
            repeat with x from 1 to (count windows)
                set windowPosition to position of window x
                set windowSize to size of window x
                set position of window x to {0, 0}
                set size of window  to {100, 100}
            end repeat
        end tell
    end repeat
end tell
Run Code Online (Sandbox Code Playgroud)

注意:脚本需要访问辅助设备(AfAD):
"系统首选项"→"通用访问"→"启用辅助设备访问"

编辑(回复评论)

从AppleScipt启用AfAD可能会改善用户体验,但是每次执行脚本时都不会这样做,只有在禁用AfAD的情况下才启用AfAD.在不通知用户的情况下启用功能是不好的做法,提示用户启用AfAD的权限.

例:

set AccesEnables to do shell script "[ -e \"/private/var/db/.AccessibilityAPIEnabled\" ] && echo \"Yes\" || echo \"No\""
if (AccesEnables is equal to "No") then
    set askUser to display dialog "This application requires access for assistive devices. Enable this feature?" default button 2
    set answer to button returned of askUser
    if answer is equal to "OK" then
        do shell script "touch /private/var/db/.AccessibilityAPIEnabled" with administrator privileges
    else
        close
    end if
end if
Run Code Online (Sandbox Code Playgroud)