4

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

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

奇怪的是,如果您输入字符串文字,则激活应用程序命令可以工作,但如果您将字符串变量传递给它,它将不会激活应用程序。任何想法为什么?

4

1 回答 1

7

你的脚本对我有用。使用字符串变量激活应用程序在任何版本的 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

如果您还从激活行中删除“应用程序”,您甚至不需要子例程中的“作为文本”......

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 是最前面的应用程序,而不是您认为最前面的应用程序。很难检测到何时发生这种情况,但我怀疑这可能发生在您身上。所以这里有一个子程序,我使用 get the frontmost 应用程序。这确保了 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
于 2012-10-27T06:57:32.590 回答