OSX Tahoe:对System Events的调用在Script Editor中能正常工作,但在导出的应用程序中却不起作用
我有一个用AppleScript编写的脚本,用来操作窗口的位置。它对 “System Events” 应用进行了大量的读写信息调用。目标是识别活动应用的窗口并自动移动/调整大小。下面给出一个在脚本编辑器中能正常工作的调用示例,但导出为应用程序并执行时却失败。
tell application "System Events"
get position of front window of (first process whose frontmost is true)
end tell
我基本上想要识别所选的窗口并把它移动过去。一旦把基础功能实现后,我会再加上花里胡哨的功能,但移动所选窗口是核心。
我认为这条调用是在获取前台进程中最前面的窗口的位置,那里应该就是所选的窗口。就像我说的,它在脚本编辑器中运行良好,但导出成应用后就会抛出无效索引错误。
来自Apple的文档……
errAEIllegalIndex = -1719, / index is out of range in a put operation /
有何建议,可能是什么原因吗?
谢谢,
Tom
解决方案
如果把你的脚本保存为一个应用并双击运行,且你引用的代码在其中能运行,那么首先成为前台的进程就是应用本身——而应用本身是没有窗口的。因此会失败。
一个更好的测试方式会是这样的:
tell application "System Events"
tell application "Finder" to activate
tell application "Finder" to make new Finder window
get position of front window of (first process whose frontmost is true)
display dialog result as text
end tell
这样做其实是在测试阶段确保前台应用确实有一个前端窗口。果然,如果把它做成一个应用,并且经过它会触发的各种沙盒/权限提示,它作为一个应用就能正常工作。
你代码的一个更安全的版本可能像这样:
tell application "System Events"
get first process where it is frontmost
get windows of result
if (count result) is greater than 0 then
get first item of result
get position of result
end if
end tell
这样只有在存在窗口、并且可以获取位置时才返回位置;如果没有,就不做任何事,也不会造成任何损害。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。