当您从笔记本电脑上拔下分辨率高于MacBook的外部监视器时,窗口大多会保留其宽度,但大小被剪裁为MacBook屏幕的(较小)高度。当您再次插入监视器时,它们的大小仍然非常小,这很令人沮丧。
我的问题是:是否有任何方法可以遍历所有打开的窗口,保存它们的大小,并在再次插入监视器后恢复它们?
我的问题是:是否有任何方法可以遍历所有打开的窗口,保存它们的大小,并在再次插入监视器后恢复它们?
代码:
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
注意:该脚本需要开启辅助功能设备(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
对于这个问题,最简单的解决方案是使用AppleScript,详见Anne的回答。
如果你想要把这个方法分享给不太懂如何启用辅助功能的朋友,或者更广泛地分发它,只需添加这一行:
do shell script ¬
"touch /private/var/db/.AccessibilityAPIEnabled" ¬
with administrator privileges
CFArrayRef windows =
CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly |
kCGWindowListExcludeDesktopElements,
kCGNullWindowID);
CGSConnection conn = _CGSDefaultConnection();
for (NSDictionary *window in windows) {
CGSWindow wid = (CGSWindow)[[window objectForKey:@"kCGWindowNumber"] intValue];
CGRect bounds;
CGRectMakeWithDictionaryRepresentation([window objectForKey:@"kCGWindowBounds"],
&bounds);
CGSMoveWindow(conn, wid, bounds.origin);
}
显然,这很糟糕,只有在你真正需要分发一个无法请求辅助访问的应用时才应该考虑它。
你也可以反向工程Window Server协议并直接与其通信,但这更加糟糕。
warm == warn && within == without
:温暖等于警告 && 在内部等于在外部
。 - Anne