OSX applescript - 检查焦点中的应用程序是否不是finder,否则不执行命令

OSX applescript - check if the application in focus is not finder, otherwise do not execute command

我对 applescript 有点生疏;试图找出当前处于焦点的应用程序是否是 finder,如果是,程序将退出。否则,它应该执行命令。

问题是我找不到检查当前焦点应用程序是否为 finder 的方法。是否在线搜索并且有示例显示如何使应用程序成为焦点,但我只想检索具有焦点的应用程序的名称;并检查脚本是否应该退出或继续。像这样的东西;虽然我没有命令检查焦点中的应用程序。

tell application "System Events"
    # check if finder is the process on focus
    if "Finder" is in focus then
        display dialog ("Finder is in front")
    else
        display dialog ("Finder is not in front")
    end if
end tell

这是检查 Finder 是否在最前面的一种方法:

示例 AppleScript 代码:

tell application "System Events" to set frontmostVisibleApp to ¬
    (name of every process whose frontmost is true and visible is true) as string

if frontmostVisibleApp is "Finder" then return

注意:示例 AppleScript 代码 就是这样,不包含任何 错误 适当处理。用户有责任根据需要或需要添加任何 错误处理 。看看 try statement and error statement in the AppleScript Language Guide. See also, Working with Errors.

这是你想要的语法:

tell application "System Events"
    # check if finder is the process on focus
    if frontmost of process "Finder" is true then
        display dialog ("Finder is in front")
    else
        display dialog ("Finder is not in front")
    end if
end tell

如果 Finder 不是 运行,这将引发错误,我相信您知道。这似乎不太可能发生,但如果您对此感到担心,可以修改代码:

tell application "System Events"
    # check if finder is the process on focus
    set frontProcessName to name of first process whose frontmost is true
    if frontProcessName is "Finder" then
        display dialog ("Finder is in front")
    else
        display dialog ("Finder is not in front")
    end if
end tell

无论是否有 AppleScript 字典,每个应用程序都有一个 frontmost 属性。

所以你可以简单地写(System Events不需要)

if frontmost of application "Finder" then
    display dialog ("Finder is in front")
else
    display dialog ("Finder is not in front")
end if