AppleScript获得激活的应用程序


13

display dialog("test")仅当“ Finder”应用程序当前处于焦点/活动状态时,才可以使用AppleScript 运行代码(例如)。


嗯,如果该应用程序已经处于活动状态,那么您打算通过再次激活它来完成什么?
肯特

stackoverflow.com/questions/3718520/…空闲状态虽然没有解决问题,但却很重要。
威廉

您需要澄清您的问题。对于给定的“作品”定义,我的答案中的脚本有效,即准确报告Finder是否位于最前面。
Tetsujin

@Tetsujin更新
威廉

您将如何启动Applescript应用程序?当然,双击它总是将Finder显示为“倒数第二”。更改答案-如果从“脚本编辑器”调用此选项将起作用,但是如果在Finder中双击则“失败”,因为它给出的是假阳性
Tetsujin

Answers:


18

如果从脚本编辑器中调用了脚本,这将起作用,因为它会“跳开”以检查下一个应用程序,但是如果双击Finder则将失败,因为Finder将始终排在最后一行。

tell application "System Events"
    set frontmostProcess to first process where it is frontmost
    set visible of frontmostProcess to false
    repeat while (frontmostProcess is frontmost)
        delay 0.2
    end repeat
    set secondFrontmost to name of first process where it is frontmost
    set frontmost of frontmostProcess to true
end tell

tell application (path to frontmost application as text)
    if "Finder" is in secondFrontmost then
        display dialog ("Finder was last in front")
    else
        display dialog (secondFrontmost & " was last in front")
    end if
end tell

为后代在此留下先前的答案

最初没有正确阅读问题后,重新调整了整个答案;-)

tell application "System Events"
    set activeApp to name of first application process whose frontmost is true
    if "Finder" is in activeApp then
        display dialog ("test")
    else
        display dialog ("test2")
    end if
end tell

+1尽管您提出的解决方案似乎无法按原样工作。只要应用程序处于打开状态,我就可以进行“测试”,并且不一定处于活动状态。
威廉

重新思考…编辑的答案
Tetsujin 2015年

完成重写后,现在我回到桌面上了-现在可以完全按照您的要求进行操作了。
Tetsujin

2
您也可以将第二个对话框命令替换为,display dialog (activeApp)以确切确认脚本认为最前面的内容。
肯特

1
请注意这一点-某些应用程序的应用程序名称(例如,tell application "app_name")与进程名称(例如,set frontmost of process "app_process" to true)不同。
BallpointBen
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.