【问题标题】:Show/hide Finder, and create new window if none exist via AppleScript显示/隐藏 Finder,如果不存在则通过 AppleScript 创建新窗口
【发布时间】:2020-09-29 21:22:18
【问题描述】:

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

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

问题(我认为这是检测现有 Finder 窗口存在的竞争条件)导致该脚本频繁创建新的 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

【问题讨论】:

    标签: applescript finder keyboard-maestro


    【解决方案1】:

    请试试这个更简单的语法,它只使用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
    

    编辑:

    要运行 Keyboard Maestro 宏,请打开 Keyboard Maestro Editor,选择宏,然后从“编辑”菜单中选择“复制为”>“复制 UUID”。

    然后在 AppleScript 中编写

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

    用复制的真实 UUID 替换 &lt;Script-UUID&gt;

    【讨论】:

    • vadian,我会使用 open 代替 reveal,就像 OP 中的 code 一样。
    • vadian - 主窗口打开后,如何键入以下键盘命令:cmd+ctrl+opt+shift+d?这是 Keyboard Maestro 中的一个组合,可以将窗口定位在特定尺寸和屏幕上的特定位置。我尝试过使用系统事件和击键,但即使不需要显示主页,它似乎也能执行。为了澄清,我只想定位 new 窗口。如果有超过 0 个窗口,就显示它们。
    【解决方案2】:

    最终我需要在运行 count windows 命令之前激活 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多