2012-10-27 54 views
2

我正在嘗試編寫一個腳本來記錄當前應用程序,切換到另一個應用程序,執行一些任務並返回到原始應用程序。這是我使用應用程序作爲變量激活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 

奇怪的是,如果你在一個字符串類型的激活申請指令的工作,但如果你傳遞一個字符串變量,它不會激活該應用程序。任何想法爲什麼?

回答

2

您的腳本適用於我。使用字符串變量激活應用程序一直在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是最前面的應用程序,而不是您認爲是最前面的應用程序。發生這種情況時很難察覺,但我懷疑這可能發生在你身上。所以這裏有一個子程序,我使用獲取最前面的應用程序。這確保了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 
+0

我實際上運行的代碼更簡單得像你的版本,它也適用於我。但是當我在兩者之間做其他事情時,它只是停止工作,爲什麼蘋果電腦很糟糕? http://pastebin.com/gwH99wws – SwiftMatt

+0

我在我的帖子中添加了一個編輯部分來解釋一些東西。看到了。 – regulus6633