2011-03-13 70 views
11

我使用這個代碼來獲取窗口標題:MacOSX的:獲得最重要的窗口標題

tell application "System Events" 
    set frontApp to name of first application process whose frontmost is true 
end tell 

tell application frontApp 
    set window_name to name of front window 
end tell 

然而,這種失敗在某些情況下。很明顯,它沒有打開的窗口,但沒有問題。但是,在某些情況下,例如對於Texmaker,它會失敗並顯示錯誤。它也不適用於預覽。

無論如何,甚至在像Texmaker這樣的情況下,怎樣才能獲得窗口標題?

回答

17

這似乎始終工作:

global frontApp, frontAppName, windowTitle 

set windowTitle to "" 
tell application "System Events" 
    set frontApp to first application process whose frontmost is true 
    set frontAppName to name of frontApp 
    tell process frontAppName 
     tell (1st window whose value of attribute "AXMain" is true) 
      set windowTitle to value of attribute "AXTitle" 
     end tell 
    end tell 
end tell 

return {frontAppName, windowTitle} 

上心從here

+1

我在嘗試修改相關任務的代碼時遇到了一些麻煩,並認爲我會在此指出。如果你想在一個特定的程序上測試這個,你可能需要首先「告訴application processName激活」,這樣processName實際上是最前面的,而AXMain不會出錯。 – 2013-09-09 00:10:19

+0

嗨,阿爾伯特,在'set windowTitle'後面加上了一行:'set level to 3',以使它「始終在最上面」,但它沒有做任何事情。你能幫我解決這個問題嗎 - 我正在試圖將這個主題應用到這裏 - http://www.macscripter.net/viewtopic.php?id=30100 - 到這裏。 – Noitidart 2016-09-03 18:31:29

+0

@Noitidart:你應該問一個單獨的問題。 – Albert 2016-09-03 21:58:44

2

給下面的腳本一試:

tell application "System Events" 
    set window_name to name of first window of (first application process whose frontmost is true) 
end tell 

我沒有驗證它適用於TextMaker,雖然。

+0

好的,它適用於Texmaker,但預覽失敗。 – Albert 2011-03-14 00:52:02

+0

如果您打開圖像,它只會導致預覽失敗。如果您打開PDF,它適用於預覽。 – Albert 2011-03-14 00:55:19

+0

當我們最小化特定應用程序時,這不起作用。例如:如果我使用chrome瀏覽器,並且如果我將它最小化,那麼它將繼續將frontAppName報告爲chrome。或者換句話說,當應用程序最小化時,焦點只保留在該應用程序上。 – 2016-09-12 07:25:50

4

大廈關閉艾伯特的回答,我不是做

global frontApp, frontAppName, windowTitle 

set windowTitle to "" 
tell application "System Events" 
    set frontApp to first application process whose frontmost is true 
    set frontAppName to name of frontApp 
    set windowTitle to "no window" 
    tell process frontAppName 
     if exists (1st window whose value of attribute "AXMain" is true) then 
      tell (1st window whose value of attribute "AXMain" is true) 
       set windowTitle to value of attribute "AXTitle" 
      end tell 
     end if 
    end tell 
end tell 

return {frontAppName, windowTitle} 

這是一個黑客,我沒有經驗,但好處是,如果沒有窗口它不會崩潰。