为什么以下Applescript会隐藏脚本编辑器?
tell application "Last.fm" to launch
tell application "System Events" to tell process "Last.fm" to keystroke "h" using command down
我发现这段代码会隐藏“Last.Fm”,但也会隐藏脚本编辑器。理想情况下,我想将keystroke "h"
替换为keystroke "w"
,但后来出现错误:
The document can’t be closed while the script is running.
为什么我编写的脚本会影响脚本编辑器?
答案 0 :(得分:1)
我没有Last.fm,所以我尝试了这个:
tell application "TextEdit" to launch
delay 2
tell application "System Events" to tell process "TextEdit" to keystroke "h" using command down
果然,确实如此,TextEdit被隐藏了,但是脚本编辑器也是如此。
然后我尝试了这个:
tell application "TextEdit" to launch
tell application "TextEdit" to activate
delay 2
tell application "System Events" to tell process "TextEdit" to keystroke "h" using command down
隐藏了TextEdit,但脚本编辑器却没有。所以我猜这也会对你的代码有所帮助。将目标应用程序放在最前面似乎是至关重要的(毕竟这具有一定的意义)。
答案 1 :(得分:0)
您在此尝试实现的功能是什么?这是整个剧本吗?你想让last.fm启动,然后理想情况下关闭窗口吗?
tell application "System Events" to tell process
不能正常工作,因为它具有很强的误导性 - 它 实际上不会将击键指向某个特定的应用程序,按键会在任何地方发生,无论它是什么时候都会被击中"告诉流程"声明,这很烦人。
我不使用last.fm,但其中任何一个都适用于我:
tell application "TextEdit"
launch
activate
end tell
delay 0.1
tell application "System Events"
keystroke "w" using command down
end tell
或
tell application "TextEdit"
launch
activate
end tell
delay 0.1
tell application "System Events"
click menu item "Close" of menu 1 of menu bar item "File" of menu bar 1
end tell
请注意,如果您计划从键盘命令或脚本菜单运行脚本,并且不希望它将焦点转移到last.fm,您可以让它启动,关闭窗口(或隐藏它),然后在脚本运行时返回到前端应用程序:
set appPath to the path to the frontmost application
tell application "Finder"
set appName to the name of file appPath
set appName to text 1 thru ((offset of "." in appName) - 1) of appName
end tell
tell application "TextEdit"
launch
activate
end tell
delay 0.1
tell application "System Events"
keystroke "w" using command down
end tell
tell application appName to activate