使用应用程序作为变量激活Applescript中的应用程序

时间:2012-10-27 05:05:45

标签: applescript

我正在尝试编写一个记录当前应用程序的脚本,切换到另一个应用程序,执行某项任务,然后返回到原始应用程序。这就是我所拥有的

set currentApp to my getCurrentApp()
activate application "Safari"
# Some task
activate application currentApp

to getCurrentApp()
set front_app to (path to frontmost application as Unicode text)
set AppleScript's text item delimiters to ":"
set front_app to front_app's text items
set AppleScript's text item delimiters to {""} --> restore delimiters to default value
set item_num to (count of front_app) - 1
set app_name to item item_num of front_app
set AppleScript's text item delimiters to "."
set app_name to app_name's text items
set AppleScript's text item delimiters to {""} --> restore delimiters to default value
set MyApp to item 1 of app_name
return MyApp
end getCurrentApp

奇怪的是,如果键入字符串文字,则激活应用程序命令有效,但如果将字符串变量传递给它,则不会激活应用程序。有什么想法吗?

1 个答案:

答案 0 :(得分:5)

你的脚本适合我。使用字符串变量激活应用程序始终适用于任何版本的OSX ...因此您遇到了一些不同的问题。问题不在您显示的代码中。

尽管您的代码有效,但您可以像这样缩短getCurrentApp()子例程......

set currentApp to my getCurrentApp()
activate application "Safari"
delay 1
activate application currentApp

to getCurrentApp()
    return (path to frontmost application as text)
end getCurrentApp

如果您还从激活线中删除“应用程序”,您甚至不需要在子程序中使用“as text”...

set currentApp to my getCurrentApp()
activate application "Safari"
delay 1
activate currentApp

to getCurrentApp()
    return (path to frontmost application)
end getCurrentApp

毕竟说完了,你的代码看起来就像这样......

set currentApp to path to frontmost application
activate application "Safari"
delay 1
activate currentApp

编辑 :有时当您尝试获取最前端的应用程序时,您运行的AppleScript是最前面的应用程序,而不是您认为最重要的应用程序。很难发现这种情况何时发生,但我怀疑这可能发生在你身上。所以这是一个子程序,我使用得到最前面的应用程序。这可确保AppleScript不会作为最前面的应用程序返回。试一试,看看它是否有帮助......

on getFrontAppPath()
    set frontAppPath to (path to frontmost application) as text
    set myPath to (path to me) as text

    if frontAppPath is myPath then
        try
            tell application "Finder" to set bundleID to id of file myPath
            tell application "System Events" to set visible of (first process whose bundle identifier is bundleID) to false

            -- we need to delay because it takes time for the process to hide
            -- I noticed this when running the code as an application from the applescript menu bar item
            set inTime to current date
            repeat
                set frontAppPath to (path to frontmost application) as text
                if frontAppPath is not myPath then exit repeat
                if (current date) - inTime is greater than 2 then exit repeat
            end repeat
        end try
    end if
    return frontAppPath
end getFrontAppPath
相关问题