告诉不同的应用程序 close/hide 时隐藏脚本编辑器

Script Editor hiding when telling a different application to close/hide

为什么下面的 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 "w" 替换 keystroke "h" 但随后出现错误:

The document can’t be closed while the script is running.

为什么我写的脚本会影响脚本编辑器?

我没有 Last.fm,所以我尝试了这个:

tell application "TextEdit" to launch
delay 2
tell application "System Events" to tell process "TextEdit" to keystroke "h" using command down

果然,确实如此,TextEdit 被隐藏了,但 Script Editor 也被隐藏了。

然后我试了这个:

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 已隐藏,但脚本编辑器未隐藏。所以我想这对您的代码也有帮助。将目标应用放在最前面似乎是至关重要的(毕竟这有一定的意义)。

您要在此处实现的功能是什么?这是整个脚本吗?您希望 last.fm 启动,然后理想情况下关闭 window?

tell application "System Events" to tell process

不起作用,因为它具有高度误导性 - 它 不会 实际上将击键指向特定的应用程序,无论击键是什么,击键都会去任何地方。 "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,您可以让它启动,关闭window(或隐藏它),然后 return 当脚本为 运行:

时,您会转到前端应用程序
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