macOS Tahoe:AppleScript 导出为 app 后为何出现 -1719 错误?
先确认导出的 app 实际选中了哪个进程
这段代码有一个前提:当前前台进程必须有可通过 System Events 访问的窗口。找到了前台进程,也未必能取得它的 front window。
可以先检查这种情况:启动导出的 app 后,前台进程变成了这个 app,而它没有可访问的窗口。此时读取 front window 可能出现 -1719。在 Script Editor 中运行时,前台进程及其窗口可能不同,因此同一表达式可能得到不同结果。
这只是一个需要验证的诊断方向。仅凭现有代码,无法确定实际选中了哪个进程,也不能认定这是 macOS Tahoe 的系统问题。
把进程选择和窗口访问分开检查
先用下面的代码查看前台进程名称,以及它暴露给 System Events 的窗口数量:
tell application "System Events"
set targetProcess to first process whose frontmost is true
set targetProcessName to name of targetProcess
set targetWindowCount to count of windows of targetProcess
end tell
set diagnosticText to "前台进程:" & targetProcessName & return & ¬
"可访问窗口数:" & (targetWindowCount as text)
display dialog diagnosticText
分别在 Script Editor 和导出的 app 中运行这段代码,比较结果。代码先读取进程名称和窗口数量,再显示对话框,避免对话框影响本次采样。
如果导出的 app 显示自身进程,且窗口数为 0,就能解释为什么无法取得 front window。如果显示的是目标应用,而窗口数仍为 0,则需要进一步检查目标窗口是否存在、能否通过辅助功能接口访问。
在访问窗口前增加检查
下面的写法保留原来的选择逻辑,并在窗口不存在时给出明确错误:
tell application "System Events"
set targetProcess to first process whose frontmost is true
set targetProcessName to name of targetProcess
if (count of windows of targetProcess) is 0 then
error ("前台进程没有可访问的窗口:" & targetProcessName)
end if
tell targetProcess
set targetWindow to front window
set originalPosition to position of targetWindow
-- 示例:将窗口移动到指定坐标
set position of targetWindow to {100, 100}
return originalPosition
end tell
end tell
这样可以避免在没有窗口时直接访问 front window,但仍要确认 targetProcess 是你想操作的应用。
让目标应用的选择方式保持明确
如果启动脚本 app 改变了前台应用,脚本查询 frontmost 时,就可能已经错过用户原先选中的窗口。重复查询或增加延迟,都不能可靠地恢复此前的选择。
可以按使用方式处理:
- 对于固定目标应用,明确指定进程,再检查它的窗口。
- 对于“移动当前窗口”的快捷操作,选择能在读取目标时保留目标应用前台状态的触发方式。
- 如果触发流程支持传递目标信息,先记录目标进程标识,再让后续脚本使用该标识。
例如,排查时可以先打开 TextEdit 的一个文稿窗口,再暂时将进程选择语句改为:
set targetProcess to first process whose name is "TextEdit"
将这行代码放在 tell application "System Events" 内,替换原来的前台进程选择语句。TextEdit 必须已经运行;这里只是以它为明确目标的示例。
如果指定进程后可以取得窗口,而使用 frontmost 时失败,就可以继续检查启动过程中的前台应用变化。
注意错误码与权限的区别
原代码执行的是读取 position。给出的错误定义注释虽然包含 put operation,也不能据此认定设置窗口位置失败。应先拆开表达式,确认错误发生在选择进程、取得窗口还是读取位置时。
如果出现明确的辅助功能或自动化授权错误,再检查导出的 app 是否拥有相应权限。Script Editor 的授权情况不能直接代表导出 app 的授权情况,也不能仅凭 -1719 判断权限不足。
即使成功取得窗口,也不代表所有应用窗口都允许修改 position 或 size。读取、移动和调整大小应分别验证。
备注:内容仅供参考。
