显示/隐藏查找器,如果不存在,则通过AppleScript创建新窗口



我想创建一个AppleScript,通过键盘大师中的键盘命令触发,允许我直接切换显示或隐藏Finder窗口。如果在切换以显示 Finder 时,如果没有现有窗口,请创建一个并将其打开到我的主目录。

以下 AppleScript 有效。但是,激活查找器和检测是否有任何打开的窗口之间似乎存在竞争条件if not (window 1 exists),因此delay 0.5

该问题(我认为这是检测现有 Finder 窗口是否存在的竞争条件(导致此脚本在已经存在时经常创建新的 Finder 窗口。if not (window 1 exists)并不总是正确的。

任何想法、调整或肯定,即这只是它的方式,将不胜感激!

tell application "System Events"
set activeApp to name of application processes whose frontmost is true
if ((activeApp as string) is equal to "Finder") then
set visible of process "Finder" to false
else
tell application "Finder"
activate
delay 0.5
if not (window 1 exists) then
make new Finder window
set thePath to POSIX file "/Users/jon"
set the target of the front Finder window to folder thePath
end if
end tell
end if
end tell

请尝试这个更简单的语法,它只使用Finder术语

tell application "Finder"
if frontmost then
set visible of process "Finder" to false
else
if (count windows) is 0 then reveal home
activate
end if
end tell

编辑:

要运行键盘大师宏,请打开键盘大师编辑器,选择宏,然后从编辑菜单中选择复制为>复制 UUID。

然后在AppleScript中写入

tell application "Keyboard Maestro Engine" to do script "<Script-UUID>"

<Script-UUID>替换为复制的真实 UUID

最终,我需要在运行计数窗口命令之前激活 Finder,否则我会得到不一致的窗口计数。有时即使已经打开了窗口,它也将是 0。到目前为止,这段代码对我来说效果很好。

tell application "Finder"
if frontmost then
set visible of process "Finder" to false
else
activate
if (count windows) is 0 then
open home
tell application "Keyboard Maestro Engine" to do script "<Script-UUID>"
end if
end if
end tell

最新更新